Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Is there a way to show multiple metrics in 1 SQL pivot operator. Basically, I have the Table1 and want the desired results is the Table2 format.
```
Table1
ACCOUNTS YEAR REVENUE MARGIN
ACCOUNT1 2012 100 50
ACCOUNT1 2013 104 52
ACCOUNT1 2014 108 54
ACCOUNT2 2012 112 56... | ```
DECLARE @t TABLE
(
ACCOUNTS NVARCHAR(MAX) ,
YEAR INT ,
REVENUE INT ,
MARGIN INT
)
INSERT INTO @t
VALUES ('ACCOUNT1', 2012, 100, 50 ),('ACCOUNT1', 2013, 104, 52 ),
('ACCOUNT1', 2014, 108, 54 ),('ACCOUNT2', 2012, 112, 56 ),
('ACCOUNT2', 2013, 116, 58 ),('ACCOUNT2', 2014... | You could do something like this:
```
SELECT
Table1.ACCOUNTS,
SUM(CASE WHEN Table1.[YEAR]=2012 THEN Table1.REVENUE ELSE 0 END) AS REVENUE_2012,
SUM(CASE WHEN Table1.[YEAR]=2013 THEN Table1.REVENUE ELSE 0 END) AS REVENUE_2013,
SUM(CASE WHEN Table1.[YEAR]=2014 THEN Table1.REVENUE ELSE 0 END) AS REVENUE_2... | SQL Pivot for Multiple Metrics by Year | [
"",
"sql",
"sql-server",
"pivot",
""
] |
I need to find the sum of values for each month and then find the max value for the months. I am a bit stumped and not sure what to do.
```
My customer wants it formatted a particular way:
Activity | JUN | JUL | AUG | MIN | MAX | AVG
jogging | 232 | 32 | 343 | 32 | 343 | 202
Here is my ta... | Your query is a bit too complicated. This, for example:
```
CASE
WHEN DECODE(TO_CHAR((TRUNC(date)), 'MON'),'AUG','AUG') IN 'AUG'
THEN 1
ELSE 0
END
```
could be rewritten as:
```
CASE WHEN TO_CHAR(date, 'MON') = 'AUG' THEN 1 ELSE 0 END
```
or even:
```
DECODE(TO_CHAR(date, 'MON'), 'AUG', 1, 0)
```
In o... | For MIN/MAX you could use GREATEST and LEAST, if you just need to select values from the result.O you can use the MIN,MAX and AVG function to aggregate the values directly from the source data.
<http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions001.htm>
Also you might want to look into using subqueries, ... | find sum of values by month then find max sum of months | [
"",
"sql",
"database",
"oracle",
"max",
""
] |
I have a problem in parsing my last name and first name in a table. My code:
```
SELECT value,
substr(value,instr(value,' ',1),instr(value,' ',2)-2) last_name,
FROM (SELECT 'Matt Ryan, QB' value
FROM dual);
```
If I write `'Andrew Luck, QB'` it parses properly the last name. But when I write `'Ma... | Please consider using regular expression. I think this should solve your problem.
```
SELECT value,
REGEXP_SUBSTR(value,
'\w+\s+(\w+\s+\w+|\w+),',1,1,NULL,1) last_name
FROM (
SELECT 'Matt Ryan, QB' value FROM dual
);
```
Check this [fiddle](http://sqlfiddle.com/#!4/9eecb/1632/0) | You're misusing the index parameter that you're passing to `instr`, plus you should remove the comma that comes after "last\_name". Try:
```
SELECT value,
substr(value, instr(value,' ')+1, instr(value,' ',instr(value,' '))-1) last_name
FROM (
SELECT 'Matt Ryan, QB' value FROM dual
);
```
**[Link to fiddle](http:... | substr SQl function | [
"",
"sql",
"oracle",
"substring",
""
] |
I've got a Sqlite database with close to 500,000 rows worth of access log information in it. I'm using it for aggregate information like "number of times each ip has hit the site", or "percentage of hits were POST", etc.
I wrote a SQL query that gathers how many times each IP address has hit the site, where the number... | Use `union all`, of course.. but that doesn't answer "the problem".
This issue is the the second query "returns multiple" (just like the first query) because the `group by` is by IP, of which there are many. That is, there is a resulting tuple *per group*, independent of any operation in the select output clause.
The... | Can you use a variable to hold this information?
```
DECLARE @num INT
SET @num = (select count(*)
from records
group by ip_address
having count(*) > (select count(ip_address) from records) * .01)
```
Then do your regular query
```
select ip_address, count(ip_address)
from recor... | SQL Union "All Other" Row | [
"",
"sql",
"sqlite",
"union",
""
] |
```
CREATE TABLE Permission (
permissionID INTEGER PRIMARY KEY UNIQUE,
user INTEGER
location INTEGER
);
```
I don't want to have user or location to be `UNIQUE` because I can have multiple rows with user containing the same data, or multiple rows with location containing the same data. I just... | Declare a unique constraint on (user, location).
```
CREATE TABLE Permission (
permissionID integer primary key,
user integer not null,
location integer not null,
unique (user, location)
);
```
```
sqlite> insert into Permission (user, location) values (1, 2);
sqlite> insert into Permission (user, loc... | What you essentially want to do is to make the **combination of user and location** unique across you table.
There are several options to achieve that and I will describe these options in the order you should consider them, as the former options are more natural than the latter.
## Option 1: Have a unique constraint i... | SQLite: Preventing Duplicate Rows | [
"",
"sql",
"database",
"sqlite",
""
] |
I have 3 tables listing below:
Table\_A:
```
order_number | header_id
123 | 80001
```
Table\_B
```
header_id | line_id | quantity
80001 | 10001 | 1
80001 | 10002 | 3
80001 | 10003 | 5
```
Table\_C
```
header_id | line_id | hold_price_id | released_flag
80001 | 10... | You need to learn to use proper explicit `join` syntax. A simple rule: never use commas in the `from` clause. *Always* use explicit `join`s:
```
SELECT A.order_number, A.header_id, B.line_id, B.quantity,
C.hold_price_id, C.released_flag
FROM Table_A a JOIN
Table_B b
ON a.header_id = b.header_id JOIN
... | You haven't joined all of the common keys, so you are getting Cartesian results. You needs to join a to c with header id, like so
```
SELECT A.order_number, A.header_id, B.line_id, B.quantity, C.hold_price_id, C.released_flag
FROM Table_A a,
Table_B b,
Table_C c
WHERE a.header_id = b.header_id
AND c.line_i... | Joining 3 tables Oracle SQL | [
"",
"sql",
"oracle",
"join",
""
] |
I want to get the total current sales for the month by category. I also wanted to display all the `category_name` (including cars) even though an `item_id` of that `category_id` is not present on my `sales_tbl` or gives $0.00 sales like..
```
category_name | subTotalSales_ofMonth
------------------------------------... | You need to use an outer join. Since all your categories are stored in the `category_tbl` table, that table should be on the outer side of the join. One way to make it so is to change the order of your joins and use `LEFT JOIN` in both cases. You will also need to move the `WHERE` condition to one of the `ON` clauses:
... | Full outer join will give you your desired result (although it will also grab NULLs from category\_name):
```
SELECT c.category_name, SUM(amount) AS subTotalSales_ofMonth
FROM sales_tbl sa
FULL OUTER JOIN item_out_tbl io ON io.item_id=sa.item_id
FULL OUTER JOIN category_tbl c ON io.category_id=c.category_id... | SELECT value non-existing on the first JOIN | [
"",
"mysql",
"sql",
""
] |
What I'm trying to is create a table that will keep track of users who report a comment on a website. Right now, I have a table that would look something like this:
```
id | num_reports | users
-----------------------------------
12345 1
12489 4
```
For this table, I'd like id to be unique ... | That's the right way to do it. Here is what you should have:
```
USERS COMMENTS
+---------+------+ +------------+---------+------------+---------------------+
| id_user | name | | id_comment | id_user | id_article | date |
+---------+------+ +------------+---------+------------... | Are you making datawarehouse? Normally quantity of reports for the websites are not saved. They are calculated on the fly by taking COUNT(\*) by the website\_id from the table where reports are saved. There you can save user who made this report. And then you can play by taking total of reports, or total of reports by ... | MySQL- List inside of a column | [
"",
"mysql",
"sql",
"database",
""
] |
Suppose I have a table containing a month's transaction data with `transaction_time` stored in a `DATETIME` field.
I want to get all the transactions that occurred between `12:00:00` and `13:00:00`, irrespective of the day. `WHERE transaction_time BETWEEN x AND y` would have to be date-specific, but I need that same t... | You can filter on the result of applying MySQL's [`HOUR()`](http://dev.mysql.com/doc/en/date-and-time-functions.html#function_hour) function to your `DATETIME` value:
```
WHERE HOUR(transaction_time) = 12
```
If you need to filter across more exact time ranges, you could convert the times to seconds as follows:
```
... | You have two time constraints. The first is to restrict the dates to a particular month. Assume we get the first day of the month as a date parameter:
```
where transaction_time >= :searchMonth
and transaction_time < Date_Add( :searchMonth, interval 1 month )
```
Now we're only looking at rows from that month.... | Getting data of everyday's same time period | [
"",
"mysql",
"sql",
""
] |
I have some data that has to be measured which are not in any table. I can not insert it to a table nor I can create any table and insert these data. So I used dual like the following to get that table. I used this to join with other tables.
```
with movie_genre as
(
select '10' as "id", 'action' as "genre" from dual
... | You can pass the genre as string in the order you want and use regular expression to generate the movie\_genre table.The [sql fiddle here](http://sqlfiddle.com/#!4/9eecb/1736)
```
with movie_genre as
(
select level * 10 as id, regexp_substr(genre,'[^,]+',1,level) as genre
from
(
select ('action,horror,comedy,adv... | If you need to get the full list, you want a `cross join`, with some additional logic:
```
with movie_genre as (
select '10' as "id", 'action' as "genre" from dual union all
select '20' as "id", 'horror' as "genre" from dual union all
select '30' as "id", 'comedy' as "genre" from dual union all
... | How to create a temporary / dynamic / virtual table when a SQL runs in Oracle? | [
"",
"sql",
"database",
"oracle",
""
] |
So the sql code looks like this:
```
UPDATE
tbl1
SET
LastModifiedDate = GETDATE(),
col1 = 'Closed',
LastModifiedBy = 'usr'
WHERE
col2 = 'xxx'
AND
col1 NOT LIKE '%Closed%'
AND
DATEDIFF(day, DateTimeOfInsert, GETDATE()) > 30
AND
col3 NOT IN
(SELECT
col3
FROM
... | The trigger you've shown is indeed broken. Something like this:
```
CREATE TRIGGER trg_tbl1_closeAction
ON tbl1
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON
INSERT INTO tbl2
(tbl_1_ID, col4, usr)
select i.ID, '10', tu.id
from inserted i
LEFT OUTER JOIN tbl3 tu ON tu.usr=i.LastModified... | Datediff is a subquery. In your case, it is probably returning more than one value (more than one record). Moreover, it is probably returning one value for each day or DateTimeOfInsert you have (perhaps both, I am unfamiliar with your schema, of course).
As the error states, you cannot use '<' on a subquery that retur... | I can't update multiple records in SQL | [
"",
"sql",
"sql-server",
""
] |
I have a table with the following schema :
```
+---------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | a... | Mysql supports multi-table deletes, so a straightforward join can be used:
```
delete t1
from mytable t1
join mytable t2 on t1.id > t2.id
and ((t1.system_one_id = t2.system_one_id
and t1.system_two_id = t2.system_two_id)
or (t1.system_one_id = t2.system_two_id
and t1.system_two_id = t2.system_one_id))
``... | Here is a statement (hopefully) selecting all ids of duplicate records, you only need to wrap it with a delete command (that´s your part). ;-)
```
select A.ID from MYTABLE A
left join MYTABLE B on
(
(A.SYSTEM_ONE_ID = B.SYSTEM_ONE_ID and A.SYSTEM_TWO_ID = B.SYSTEM_TWO_ID)
or
(A.SYSTEM_ONE_ID = B.SYSTEM_... | Delete duplicates from two columns | [
"",
"mysql",
"sql",
""
] |
I have a table like so
```
Id | Type | Value
--------------------
0 | Big | 2
1 | Big | 3
2 | Small | 3
3 | Small | 3
```
I would like to get a table like this
```
Type | Last Value
--------------------
Small | 3
Big | 3
```
How can I do this. I understand there is an SQL Server method called **LAST\_VA... | The most efficient method might be `not exists`, which uses an anti-join for the underlying operator:
```
select type, value
from likeso l
where not exists (select 1 from likeso l2 where l2.type = l.type and l2.id > l.id)
```
For performance, you want an index on `likeso(type, id)`. | You can do it using rownumber:
```
select
type,
value
from
(
select
type,
value,
rownumber() over (partition by type order by id desc) as RN
) TMP
where RN = 1
```
Can't test this now since SQL Fiddle doesn't seem to work, but hopefully that's ok. | How to efficiently get a value from the last row in bulk on SQL Server | [
"",
"sql",
"sql-server",
"aggregate-functions",
""
] |
Can someone suggest a good solution to this approach.
I have 2 binary strings (1010101....) of 1024 bits in length
Now I would want to do bit operation (AND) on both to get a value whether it is greater than 0 or not.
Currently I am converting the string to hex(256) and varbinary(128)
So once I have two varbinary I... | After a long discussion I have finally figured out what input data you have. You have a varbinary(128) that is constructed from a binary string (like '1000010010101... ') that is 1024 characters long. SQL Server does not provide a ready function that does such a conversion. I have built one to allow me testing. The fol... | > If your binary numbers can convert to any numeric types this answer can help you.
**& (Bitwise AND) (Transact-SQL)**
Performs a bitwise logical AND operation between two integer values.
```
expression & expression
```
**expression**
Is any valid expression of any of the data types of the integer data type cate... | How can I do AND BIT OPERATOR between two varbinary fields in SQL | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I have two tables, `Users` and `Company`.
I want to transfer values from a `Active` column in the `Users` table to the `Active` column in the `Company` table, where the `CompanyID` in matches `ID`.
This is an example table. It has many thousands of rows, and there is 1 on 1 relationship between `Company` and `Users`:... | You can simply perform an `UPDATE` that uses a `JOIN` between the two tables like so:
```
UPDATE c
SET Active = u.Active
FROM Company c
INNER JOIN Users u ON u.CompanyId = c.ID
```
**Full working sample code:**
```
CREATE TABLE #Users
(
CompanyId INT ,
Active BIT
)
INSERT INTO #Users
( ... | That should do the trick for you.
```
DECLARE @Users TABLE (CompanyID INT, Active BIT);
DECLARE @Companies TABLE (CompanyID INT, Active BIT);
INSERT INTO @Users (CompanyID, Active)
VALUES (458, 1), (685, 1), (58, 0)
INSERT INTO @Companies (CompanyID)
VALUES (5),(3),(58),(685)
SELECT C.CompanyID, U.Active
FROM @Com... | Update a table with values from a related table | [
"",
"sql",
"sql-server",
"conditional-statements",
"transfer",
""
] |
I have a SQL Server database and having a table containing too many records. Before it was working fine but now when I run SQL Statement takes time to execute.
Sometime cause the SQL Database to use too much CPU.
This is the Query for the table.
```
CREATE TABLE [dbo].[tblPAnswer1](
[ID] [bigint] IDENTITY(1,1) NOT NUL... | Add an Index on the `ID` column and include `ShuleID`, `Mwaka`, `Swali` and `Wilaya` columns. That should help improve the speed of the query.
```
CREATE NONCLUSTERED INDEX IX_ID_ShuleID_Mwaka_Swali_Wilaya
ON tblPAnswer1 (ID)
INCLUDE (ShuleID, Mwaka, Swali, Wilaya);
``` | Just add an index on ShuleID, Mwaka, Swali and Wilaya columns. The order of columns in the index should depend on distribution of data (the columns with most diverse values in it should be the first in the index, and so on).
And if you need it super-fast, also include all the remaining columns used in the query, to ha... | SQL Statement take long time to execute | [
"",
"sql",
"sql-server",
""
] |
My sql string is off just a little bit and I need help to get it exactly right. I have tried a number of strings with no luck. [I've tried most of the examples in this thread, with no luck.](https://stackoverflow.com/questions/16550703/sql-get-the-last-date-time-record "Stackoverflow thread.") Concerning the sql, here ... | Here is a query to find the most recent date-time values by TagName
```
SELECT A.[DateTime]
,A.[TagName]
,A.[Value]
FROM [v_StringHistory] A
INNER JOIN
(SELECT MAX(B.[DateTime]) [MaxDate]
,B.[TagName]
FROM [v_StringHistory] B
GROUP BY B.[TagName]) MD
ON MD.[TagName] = A.[TagName]
... | For this particular front-end Wonderware, there are apparently some rules about how you query their tables. Luckily they have a GUI that allows you to pick and click what you want to see and then it spits out the SQL code. In this case, the code ended up being:
```
SET NOCOUNT ON
DECLARE @StartDate DateTime
DECLARE @E... | SQL Show Only the Most Recent DateTime Values | [
"",
"sql",
"sql-server-2008",
""
] |
I have a table `test` which looks like this:
```
+-------+-------+
| u1_id | u2_id |
+-------+-------+
| 1 | 2 |
| 3 | 1 |
| 2 | 1 |
| 2 | 3 |
+-------+-------+
```
And, `u1_id` and `u2_id` are both 'foreign keys' to another table `user`:
```
+----+-------+
| id | name |
+----+------... | If I correctly understood your question, I believe you need following query:
```
SELECT t2.`name`
FROM `t2`
INNER JOIN (
SELECT IF(@uid = 1, t1.u1_id, t1.u2_id) as `id`
FROM `t1`
) as `t1`
WHERE t2.id = t1.id and t1.id != @uid;
```
I tried following:
Date base create, I don't know what columns type your are... | Using @GrijeshChauhan's schema...
```
SELECT * FROM
(SELECT u1_id,u2_id FROM t1
UNION ALL
SELECT u2_id,u1_id FROM t1
) x
JOIN t2
ON t2.id = x.u1_id
WHERE x.u2_id = 2;
+-------+-------+------+-------+
| u1_id | u2_id | id | name |
+-------+-------+------+-------+
| 1 | 2 | 1 | n_foo |
| 1 | 2 ... | List all associate's names from a referred table? | [
"",
"mysql",
"sql",
""
] |
hey Guys i m working on SQL and i got this error
first i ll show you my code
```
Insert into HistoriqueEquipement (DateMHS,CodeEquipement,nomenclature) VALUES (2015-03-28, (SELECT CodeEquipement,nomenclature FROM equipement WHERE Numero_Serie =241));
```
i got the error #1241 - Operand should contain 1 column(s);
... | I think you are getting this error as the `rows` returned by the `SELECT` is more than one. So you can use a `INSERT INTO TABLE SELECT` like this:
```
Insert into HistoriqueEquipement (DateMHS,CodeEquipement,nomenclature)
SELECT CURDATE(), CodeEquipement, nomenclature
FROM equipement
WHERE Numero_Serie =241;
``` | You should use `insert . . . select`, and you can use it with a constant:
```
Insert into HistoriqueEquipement (DateMHS,CodeEquipement)
SELECT '2015-03-28', CodeEquipement
FROM equipement
WHERE Numero_Serie = 241;
```
Note:
* If you want only one row, then add `limit 1`.
* Even when using values, you ne... | #1241 Operand should contain 1 column(s) in Insert into Select | [
"",
"mysql",
"sql",
""
] |
is there any way to optimize the following MySql Query?
```
SELECT article.*
FROM article
WHERE channelid = 1
AND ((SELECT count(*) FROM article_cCountry WHERE ID1 = article.id AND ID2 = 1) = 1)
AND date < now()
AND released = "TRUE"
AND ( (uId = 0) OR ((SELECT count(*) FROM user WHERE ID = article.uId and released = ... | Try to explain your query with:
```
EXPLAIN SELECT ...
```
If you are not using any index try to put an index on the fields used in the where:
```
article.date
article.channelid
article.released
user.released
article_cCountry.id1
article_cCountry.id2
``` | I'm not sure you need to check
```
SELECT article.*, COUNT(ac.id) ac_count, COUNT(u.id) u_count
FROM article
INNER JOIN article_cCountry ac ON ac.ID1 = article.id AND ac.ID2 = 1
INNER JOIN user u ON u.ID = article.uId and u.released
WHERE
channelid = 1
AND date < now()
AND released = "TRUE"
GROUP BY article... | Slow MySQL Query / Large DB / JOIN | [
"",
"mysql",
"sql",
"database",
""
] |
I have a table with object show/click statistics.
Table has such columns: id, objectId, pageUrl, event('show' or 'click').
For example:
```
id, objectId, pageUrl, event
1, 1, /cars/, show
2, 1, /cars/, show
3, 1, /items/, show
4, 2, /cars/, show
5, 2, /items/, ... | Try this query:
```
SELECT objectId, COUNT(DISTINCT(pageUrl)) AS 'counter'
FROM Table
GROUP BY objectId
``` | ```
SELECT objectId, COUNT(*) AS count FROM ( SELECT objectId,pageUrl FROM table GROUP BY objectId,pageUrl ) z GROUP BY objectId
``` | MySQL - Count only if unique | [
"",
"mysql",
"sql",
""
] |
Is there any function to check for continuous date. I'm having problem on working with this issue below:
My table has a `datetime` column with the following data:
```
----------
2015-03-11
2015-03-12
2015-03-13
2015-03-16
```
Given start date as `2015-3-11` and end date as `2015-3-17`. I want the result as:
```
---... | I'm thinking this is somewhat a variation of **[Grouping Islands of Contiguous Dates](http://www.sqlservercentral.com/articles/T-SQL/71550/)** problem. This can be done using `ROW_NUMBER()`:
[**SQL Fiddle**](http://sqlfiddle.com/#!6/c67a0/6/0)
```
CREATE TABLE Test(
tDate DATETIME
)
INSERT INTO Test VALUES
('20... | For `MSSQL 2012`. This will return MAX continuous groups:
```
DECLARE @t TABLE(d DATE)
INSERT INTO @t VALUES
('20150311'),
('20150312'),
('20150313'),
('20150316')
;WITH
c1 AS(SELECT d, IIF(DATEDIFF(dd,LAG(d, 1, DATEADD(dd, -1, d)) OVER(ORDER BY d), d) = 1, 0, 1) AS n FROM @t),
c2 AS(SELECT d, SUM(n) OVER(ORDER BY ... | How to Select continuous date in sql | [
"",
"sql",
"sql-server",
""
] |
I have table like this:
```
IST | FILEDATE | DATE | ...
1 | 2013-2014 | 27.03.2015 10:20:47 | ...
2 | 2013-2014 | 27.03.2015 10:20:47 | ...
3 | 2013-2014 | 27.03.2015 10:20:47 | ...
1 | 2013-2014 | 28.03.2015 11:20:47 | ...
2 | 2013-2014 | 28.03.2015 11:20:47 | ...
3 | 2013-2014 | 28.03.201... | That's a typical scenario where analytical functions (aka windowing functions) are really helpful:
```
with v_data(ist, filedate, entry_date) as (
select 1, '2013-2014', to_date('27.03.2015 10:20:47','DD.MM.YYYY hh24:mi:ss') from dual union all
select 2, '2013-2014', to_date('27.03.2015 10:20:47','DD.MM.YYYY hh24... | You can first group the result:
```
select ist, max(date) date
from table
group
by ist
```
Then you can combine that result with a `select` to get all matching lines:
```
select master.*
from table master
join
( select ist, max(date) date
from table
group
by ist
) filter
on master.ist = filt... | How can I select only newest entries? | [
"",
"sql",
"oracle",
"greatest-n-per-group",
""
] |
How to truncate any table using its synonym in oracle?
```
-- in Server_A
Create Table table_a ( col int);
-- in server_B
CREATE SYNONYM syn_table_a FOR table_a@dblink_server_a;
--insert into
INSERT INTO syn_table_a values (1);
--Truncate
How to truncate table using synonym only?.
``` | **A truncate statement cannot be used on a synonym.**
> Synonyms cannot be used in a drop table, drop view or truncate
> table/cluster statements. If this is tried, it results in a ORA-00942:
> table or view does not exist
For example,
```
SQL> CREATE TABLE t(col NUMBER);
Table created.
SQL>
SQL> CREATE SYNONYM t_... | You could use dynamic SQL to do it, e.g.:
```
declare
d varchar2(1000);
begin
select 'TRUNCATE TABLE "' || table_owner || '"."' || table_name || '"'
into d
from all_synonyms
where synonym_name = 'MYSYNONYM';
execute immediate d;
end;
```
If the table is accessed via a database link, this will not work. In... | How to truncate any table using its synonym in oracle? | [
"",
"sql",
"oracle",
"truncate",
"synonym",
""
] |
Early last year I was on a project using Oracle DB and was introduced to a new querying format where you could query the results of the previous query. It was only for a few weeks we were helping on the project so so I don't recall exactly how things were written. But, it was something like the outline below. Note all ... | the form you mentioned is `subquery`,
which `may be` wrote with `join`s (depends on the query and subqueries):
```
select firstName from users where active = true;
select authors from books where authorFirstName in (previous select);
```
is equal to:
```
select books.authors
from books
join users on books.authorF... | You can use the SQL with clause to give a sub-query a name and then use that name. Example here:
[SQL WITH clause example](https://stackoverflow.com/questions/12552288/sql-with-clause-example) | What is the proper term or style called for a query of query? | [
"",
"sql",
"oracle",
""
] |
I'm trying to join three tables to pull back a list of distinct blog posts with associated assets (images etc) but I keep coming up a cropper. The three tablets are `tblBlog`, `tblAssetLink` and `tblAssets`. The Blog tablet hold the blog, the asset table holds the assets and the Assetlink table links the two together.
... | Use `OUTER APPLY`:
```
DECLARE @b TABLE ( BID INT )
DECLARE @a TABLE ( AID INT )
DECLARE @ba TABLE
(
BID INT ,
AID INT ,
Priority INT
)
INSERT INTO @b
VALUES ( 1 ),
( 2 )
INSERT INTO @a
VALUES ( 1 ),
( 2 ),
( 3 ),
( 4 )
INSERT INTO @ba
VALUES ( 1, 1, 1... | Based on your comments
> i would like to get is just one asset per blog post (top one ordered
> by Priority)
You can change your query as following. I suggest changing the join with `dbo.tblAssetLink` to filtered one, which contains only one (highest priority) link for every blog.
```
SELECT dbo.tblBlog.BID,
... | How to join three tables with distinct | [
"",
"sql",
"sql-server",
""
] |
I have a query like this
```
select * from tablename where ID in(select max(ID) from tablename )
```
I want to remove subquery to improve performace. Please suggest me,How to do it
Thank you in advanced | You don't mention your RDBMS, but in MS-SQL:
```
SELECT TOP 1 *
FROM tablename
ORDER BY ID DESC
``` | for Oracle :
```
SELECT *FROM
(
SELECT * FROM tablename ORDER BY ID desc
)
WHERE rownum <= 1 ORDER BY ID ;
```
For MS-SQL :
```
SELECT TOP 1 * FROM tablename ORDER BY ID DESC
```
For MY SQL :
```
select * from tablename order by ID desc limit 1
``` | how to remove subquery from sql involving max() | [
"",
"sql",
"sql-server",
"database",
""
] |
I'm trying to do a self join and subtract values of the same column.
```
--sum of all pageviews of circleid 0 of each device category - (sum of all
--pageviews of circleid <> 0 of each device category)
```
**Existing table - gadata:**
```
PageName DeviceCategory FKCircleId FKGAFilterKeyID PageViews
login ... | You are joining on incorrect columns. Also use `ISNULL` function in order not to get `NULL`s when no matching rows will be found in `TBL4`:
```
SELECT t3.PageName,t4.t4Circle AS Circle,
(t3.Total1-ISNULL(t4.Total2, 0)) AS Total
FROM TBL3 t3
LEFT JOIN TBL4 t4 ON t3.PageName = t4.PageName AND t4.DeviceCategory = ... | instead of the long query in question just use a `self join` only:
```
select tbl1.pagename, tbl1.devicecategory, tbl1.pageviews - tbl2.pageviews
from (select t2.pagename, t2.devicecategory, sum(t2.pageviews) as pageviews
from gadata t2
where t2.FKCircleId=0
group by t2.pagename, t2.devicecategor... | How to do left join with nulls | [
"",
"sql",
"t-sql",
"sql-server-2012",
""
] |
I'm working in rails. My model is like this:
```
class Topic < ActiveRecord::Base
has_many :topics, dependent: :delete_all
belongs_to :parent, foreign_key: 'topic_id', class_name: 'Topic'
has_many :contents
validates :name, uniqueness: true, presence: true
end
```
So I have a topic that can have many "sub-to... | Try this:
```
child_ids_with_topic_id = where.not(topic_id: nil).pluck(:topic_id)
where.not(id: child_ids_with_topic_id)
``` | ```
def self.leafs
topics.where("topic_id IS NOT NULL")
end
```
ActiveRecord 4.0 and above adds where.not so you can do this:
```
scope :leafs, -> topics.where.not(topic_id: nil)
scope :without_topics, includes(:topics).where(:topics => { :id => nil })
``` | How to convert this query to ActiveRecord logic? | [
"",
"sql",
"ruby-on-rails",
"activerecord",
""
] |
**PLEASE DO NOT MARK THE QUESTION AS DUPLICATE WITHOUT READING IT. I DID POST A SIMILAR QUESTION BUT THE STACKOVERFLOW COMMUNITY MEMBERS ASKED ME TO REPOST THE MODIFIED QUESTION SEPARATELY AS THE SOLUTION IS MUCH MORE COMPLICATED GIVEN A SMALL, SUBTLE MODIFICATION.**
Suppose you have the following schema:
```
CREATE ... | Took me a few minutes to dredge up the right CTE for this:
```
WITH ids AS (
SELECT
ID,
ID AS orig FROM Data d1 WHERE CXL IS NULL
UNION ALL
SELECT
d2.ID,
orig
FROM ids i
INNER JOIN Data d2 ON d2.CXL = i.ID
)
SELECT
orig AS [Original Id],
MAX(ID) AS [Latest Good Id]
FROM ids
GROUP BY o... | I think you can do it using a recursive CTE:
```
;WITH CTE AS (
SELECT ID AS Parent, ID, CXL, 0 AS level
FROM Data
WHERE CXL IS NULL
UNION ALL
SELECT c.Parent AS Parent, d.ID, d.CXL, level = level + 1
FROM CTE AS c
INNER JOIN Data AS d ON c.ID = d.CXL
)
SELECT Parent AS OriginalID, ID AS GoodI... | How would you find the 'GOOD' ID when cancellation is involved as well as the original ID that started it all? | [
"",
"sql",
"sql-server",
""
] |
I have created a table VQ1 using following clause.
```
CREATE VIEW VQ1 as
SELECT productid, productname, TO_CHAR(unitprice,'$9,999.99') AS "unitprice"
FROM products
WHERE unitprice > avg(unitprice)
WITH READ ONLY;
```
I am getting an error that I can not use the aggregate function `AVG()` to find the avera... | You can try this mate:
```
CREATE VIEW VQ1 AS
SELECT
productid,
productname,
TO_CHAR(unitprice, '$9,999.99') 'unitprice'
FROM
products
GROUP BY
productid
HAVING
unitprice > AVG(unitprice);
``` | Because `avg` is an aggregate function, it cannot be used in the select unless the other fields are specified in the `group by` clause.
```
create view VQ1 as
select productid, productname,
TO_CHAR(unitprice,'$9,999.99') as "unitprice"
from products,
(select avg(unitprice) as avgprice from products)
where unitprice ... | Not able use the average aggregate in view table | [
"",
"sql",
"database",
"oracle",
""
] |
Using Microsot's SQL server I want to show a list of each costumer and they spends by year and quarter. So, I have the next code:
```
SELECT CompanyName AS 'Customer', YEAR(OrderDate) AS 'Year' ,
Quarter1 = CASE(DATEPART(q, Orders.OrderDate))
WHEN 1 THEN SUM((UnitPrice*Quantity)*(1-Discount))
ELSE 0
... | wrap your query and group it by customer and year. something like this...
```
SELECT Customer,Year,SUM(Quarter1) AS Quarter1,SUM(Quarter2) AS Quarter2,SUM(Quarter3) AS Quarter3,SUM(Quarter4) AS Quarter4
FROM
(
SELECT CompanyName AS 'Customer', YEAR(OrderDate) AS 'Year' ,
Quarter1 = CASE(DATEPART(q, Orders.Orde... | use Common Table Expression [CTE](https://msdn.microsoft.com/en-IN/library/ms175972.aspx)
```
;with cte1 as
(
SELECT CompanyName AS 'Customer', YEAR(OrderDate) AS 'Year' ,
Quarter1 = CASE(DATEPART(q, Orders.OrderDate))
WHEN 1 THEN SUM((UnitPrice*Quantity)*(1-Discount))
ELSE 0
... | SQL GROUP BY quarters | [
"",
"sql",
"sql-server",
"group-by",
""
] |
I have working with two tables in sql developer to determine which customer has placed the most orders I have gotten as far as to figure out the total number of order placed by each customer, but cannot figure out how to show only the one with the MAX number of orders...
For example-
this will give me a list of all cu... | You can't use `max` like that. Instead, order by count in descending order and get the first record, like so:
```
SELECT * FROM
(select customer.cust_num, customer.cust_bizname,
COUNT(invoice.inv_num) AS "TOTAL ORDERS"
FROM customer INNER JOIN invoice ON customer.cust_num = invoice.cust_num
GROUP BY customer.cust_nu... | Use `Order BY` with `ROWNUM`
```
select *
from
(SELECT customer.cust_num,
customer.cust_bizname,
COUNT(invoice.inv_num) AS "TOTAL ORDERS"
FROM customer
INNER JOIN invoice
ON customer.cust_num = invoice.cust_num
GROUP BY customer.cust_num, customer.cust_bizname
Order by "TOTAL ORDERS" DESC
)
Where R... | Determine customer with most orders placed | [
"",
"sql",
"oracle",
"oracle-sqldeveloper",
""
] |
I am running this script on sql oracle developer:-
```
DEFINE TABLESPACE1 = "&TABLESPACE1";
CREATE TABLE "DBUSER"
(
"USER_ID" VARCHAR2(100 BYTE),
"USERNAME" VARCHAR2(100 BYTE),
"CREATED_BY" VARCHAR2(100 BYTE),
"CREATED_DATE" DATE
) TABLESPACE "&TABLESPACE1" ;
```
I am getting this error:-
```
SQL Error: ORA-0... | **NOTE** Not all `SQL*Plus` commands are necessary to run in **SQL Developer**. Also, it depends on the SQL Developer version, the latest versions have a lot of SQL\*Plus commands support.
I tested in **SQL Developer version 3.2.20.10**
`&` is used for **substitution variable** in `SQL*Plus` .
For example,
In `SQL*... | It looks like you entered a value '&TABLESPACE1' into TABLESPACE1 substitution variable. Maybe you have substitution scanning off. Try
```
SET SCAN ON
```
before your statement | SQL Error: Tablespace does not exist | [
"",
"sql",
"oracle",
"oracle-sqldeveloper",
""
] |
I have a query for example `Query1 = Select Name from table where some Criteria`.
Now this query returns a result set of course, what I want is to query the result set of this query, for example I only want the unique Names from the above query `select Distinct(Name) from Query1`. I should mention that I know I can jus... | You can use the `WITH` clause
```
WITH SomeClients AS (
SELECT
c.ID
FROM Clients c
WHERE c.Name LIKE '%hello%'
)
SELECT DISTINCT
sc.ID
FROM SomeClients sc
``` | There are several ways to solve this:
1: create a view from the first query and run the second query on the view.
2: nest both queries, like this:
```
SELECT DISTINCT [Name]
FROM (
SELECT [Name]
FROM table
WHERE some Criteria
) As InnerQuery
```
3: use a temporary table to store the resultset of the first q... | Querying the Result set of a Previous Query | [
"",
"sql",
"sql-server",
"sql-server-2012",
"subquery",
""
] |
```
1 L R
1 1 1
1 1 2
1 1 3
1 2 1
1 2 2
1 2 3
1 3 1
1 3 2
1 3 3
```
Using this query but not able to get for L column
```
Sele... | You could do a **Cartesian join** in the **row generator** query you have to generate `3 rows`. Thus, the **Cartesian product** would generate total `9 rows`.
For example,
```
SQL> WITH DATA AS
2 ( SELECT LEVEL rn FROM dual CONNECT BY LEVEL <=3
3 )
4 SELECT 1, A.rn L, b.rn R FROM DATA A, DATA b
5 /
... | ```
select 1, L, R
from (Select level R
from DUAL
Connect by level <=3),
(Select level L
from DUAL
Connect by level <=3)
``` | How to get this below output from DUAL in oracle? | [
"",
"sql",
"oracle",
""
] |
I'm new to sql and I'm writing a sql script to select data and the results will be displayed in a .csv format. For one of the fields, I'm needing to select only what is before the @ in the email address for everyone in the listing. I'm not wanting to update the records in the table.
Ex: john.doe@yahoo.com
I'm only ne... | `SELECT SUBSTR('test@example.com', 1, INSTR('test@example.com', '@')-1) FROM DUAL;`
Output:
> test | You could do:
```
select SUBSTR("test@testdomain.com", 1, INSTR("test@testdomain.com", "@")-1)
from dual
``` | How to exclude everything after an @ in SQL? | [
"",
"sql",
"oracle",
""
] |
I am working with Oracle SQL, and I have a table with an attribute POST (VARCHAR2(10 BYTE)). The data that I am given would be in the format 123.34, and I need one VARCHAR2 (123) and one NUMBER (0.34) to store this in a different table. I was trying to think of a way to do this in a select statement, but could not figu... | Can you be assured that the value will always be a `NUMBER`? If so, then just use `TO_NUMBER()`:
```
WITH t1 AS (
SELECT '123.34' AS post FROM dual
)
SELECT post_num, TRUNC(post_num), post_num - TRUNC(post_num) FROM (
SELECT TO_NUMBER(post) AS post_num FROM t1
);
```
---
If you are not sure that it will alwa... | select '123.45' num,
substr('123.45',1,instr('123.45','.')-1) wholenum,
substr('123.45',instr('123.45','.')+1) decimalpart
from dual
Output:
NUM WHOLENUM DECIMALPART
123.45 123 45 | Oracle SQL, separating a Number string to get whole number and decimal separately | [
"",
"sql",
"oracle",
""
] |
I have an accounts and a contacts table, and I am trying to find any accounts where NONE of the contacts associated with that account have a value for a certain field.
Scenario 1: Account WaffleHouse has 3 contacts, 1 of the contacts has a value in field "Field1". This account IS NOT returned in result set.
Scenario ... | You are very close - just use some aggregation (`GROUP BY`) and the `MAX` function to get what you want, like so:
```
select a.accountid
from account as a
inner join contact as c
on a.accountid = c.accountid
group by a.accountid
having MAX(isnull(c.Field1, '')) = ''
``` | Try this:
```
SELECT *
FROM Accounts a
WHERE NOT EXISTS ( SELECT *
FROM contact c
WHERE a.accountid = c.accountid
AND c.Field1 = 'TRUE' )
```
Or:
```
SELECT *
FROM Accounts a
WHERE NOT EXISTS ( SELECT *
FROM c... | Please help form this T-SQL Query to return correct Account results | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Hi I have a ms access table in the following format
```
request_date | Total_Uploaded
24/03/2015 07:42:47 | 36
24/03/2015 07:56:19 | 36
24/03/2015 08:17:28 | 4
24/03/2015 08:33:04 | 4
24/03/2015 08:39:07 | 36
24/03/2015 08:53:56 | 10
24/03/2015 09:04:26 | 16
24/03/2015 09:14:03 | ... | As this is Access, here is how:
```
SELECT
Format([request_date],"dd\/mm\/yyyy hh") AS DateHour,
Count(TableTotals.total_uploaded) AS Count_all,
Count(IIf([total_uploaded]<=10,1,Null)) AS Count_0_to_10,
Count(IIf([total_uploaded] Between 11 And 50,1,Null)) AS Count_11_to_50,
Count(IIf([total_u... | You can use [case](http://www.techonthenet.com/access/functions/advanced/case.php) inside a sum for each column. In the case you transform a value in the particular range to 1 and other values to 0. | Select Multiple counts from the same table based on range | [
"",
"sql",
"ms-access",
""
] |
I'm having trouble selecting a column from a subselect that has a shared name between two joined tables using the `ON` join expression syntax.
I have two tables, `event` and `geography` each of which has a `geography_id` column, which is the same data type, and `event.geography_id` is a foreign key into `geography` (g... | It would be a very helpful feature in SQL to be able to select all columns *except* one or more that you explicitly want to exclude. If it existed, you could have used such a feature to solve your problem by excluding `g.geography_id`. Unfortunately, such a feature does not appear to exist anywhere, in any DBMS. See <h... | Pull the predicate down into a subquery *before* you join:
```
SELECT e.event_id
FROM (SELECT * FROM event WHERE geography_id IN (1,2,3)) e
LEFT JOIN geography g ON (g.geography_id = e.geography_id);
```
The result is 100 % equivalent to your original query:
```
SELECT e.event_id
FROM event e
LEFT JOIN geogra... | Resolving an ambiguous column in a subselect | [
"",
"sql",
"postgresql",
"join",
"subquery",
"left-join",
""
] |
I record Start and End times in SQL whenever something happens to a record, basically a user opens a screen containing the information on a record, and I want to see how long the screen was opened.
I record the start time, and the end together with the stage the case is currently in for that case in a linked table sim... | You can select StartTime rows and with an inner select fill EndTime:
```
SELECT Id, Reference, Stage, StartTime,
(SELECT t1i.EndTime FROM Table1 t1i WHERE t1.Stage = t1i.Stage And t1i.StartTime IS NULL
And t1i.Id = (SELECT min(t1ii.Id) FROM t1ii WHERE t1ii.StartTime IS NULL And t1ii.Stage = t1.S... | ```
SELECT * FROM (
SELECT [Id], [Reference], [Stage], [StartTime],lead(EndTime) OVER (ORDER BY ID) AS NewEndDate FROM yourTablename
) tbl
WHERE id % 2 = 1
```
**EDIT**: This query will work in SQL Server 2012 and above versions
You can use below query if you are using older versions of SQL Server:
```
SELECT * ... | Combining rows in SQL | [
"",
"sql",
"sql-server-2008",
""
] |
I am trying to create a view in Oracle to show all rooms available in the hotel that are not booked out.
If they are booked out there will be a record in RoomBasket. So I am trying to select all rooms not in RoomBasket between the checkin and checkout dates (RoomBasket.datein, RoomBasket.dateout)
But the query kept r... | You have no predicate on your join of `Room` to `RoomType`, so you get a cross join. That is unlikely to be what you want.
Furthermore, your `union` looks like it's trying to add unrelated data to the room data. Your description of the problem suggests that you want to use the `RoomBasket` data to *filter* the other d... | Your first query is returning a different number of columns than your second query, thus they cannot be unioned. Specify the columns for the first query explicitly instead of using `SELECT *`. | Oracle union giving error | [
"",
"sql",
"database",
"oracle",
"join",
"union",
""
] |
I want to save the hassle of doing many querys for the following:
I have a table like this:
```
name, age
{
Mike, 7
Peter, 2
Mario, 1
Tony, 4
Mary, 2
Tom, 7
Jerry, 3
Nick, 2
Albert, 22
Steven, 7
}
```
And I want the following result:
```
Results(custom_text, num)
{
1 Year... | you can use below query but it `will not show the gaps` if you want gaps then the use [Linoff's answer](https://stackoverflow.com/a/29336556/3208640):
```
select t.txt, count(t.age) from
(select
case
when age<11 then concat(age ,' year')
else 'more than 10'
end txt, age
from your_table)t
group by ... | You can use `left join` and a subquery to get what you want:
```
select coalesce(concat(ages.n, ' year'), 'More than 10 year') as custom_text,
count(*)
from (select 1 as n union all select 2 union all select 3 union all select 4 union all
select 5 union all select 6 union all select 7 union all select 8 u... | How to reduce SQL queries in only one in this case | [
"",
"mysql",
"sql",
"join",
"group-by",
"having",
""
] |
I need to get all table names in SQL Server. To do this I use this code:
```
select TABLE_NAME
from INFORMATION_SCHEMA.TABLES
```
I need use dynamic database name. To do this I tried to use this code:
```
Declare @dbName varchar(50)='Learn'
use @dbname
go
select TABLE_NAME
from INFORMATION_SCHEMA.TABLES
```
B... | ```
DECLARE @dbName varchar(50)='Learn'
EXEC ('SELECT TABLE_NAME FROM ' +@dbName+'.INFORMATION_SCHEMA.TABLES');
```
OR SIMPLY:
```
SELECT TABLE_NAME FROM Learn.INFORMATION_SCHEMA.TABLES
``` | Create this stored procedure in master db and call it
```
CREATE PROCEDURE custom_query_executor
@dbName VARCHAR(50)
AS
BEGIN
DECLARE @query_string nvarchar(4000);
SET @query_string = 'select TABLE_NAME from ' + CAST(@dbName AS NVARCHAR) +'.INFORMATION_SCHEMA.TABLES';
EXEC sys.sp_executesql @query... | How to use database name dynamically in SQL Server | [
"",
"sql",
"sql-server",
""
] |
I have got table that is looking like this:
```
+------+-------+-------------+
ID_Loc Type Data
+------+-------+-------------+
ABC RMKS Hello
ABC NAM Joe Smith
ABD NAM Peter Hill
ABD RMKS Bye Bye
ABD NAM Freddy Tall
ABE NAM Loran Bennett
ABE RMKS Bye Bye
ABF ... | If you need to select the `ID_Loc` values for which there is no record matching the `'%Hello'` pattern, here's the query to do it:
```
SELECT ID_loc
FROM data_full
group by ID_Loc
having max(case
when DATA LIKE '%Hello' then 1
else 0
end) = 0;
```
This is the result: <http://sql... | you need to remove the space, added the RMKS filter as well.
```
SELECT distinct ID_loc
FROM data_full
WHERE Type= 'RMKS'
and DATA NOT LIKE '%Hello' --'%Hello%' if it can be between other text
```
EDIT:
If `ID_Loc,Type` isn't unique:
```
SELECT distinct ID_loc
FROM data_full
WHERE ID_loc NOT IN (SELECT ID_loc F... | SQL Select WHERE Column NOT LIKE across multiple lines | [
"",
"sql",
"sql-server",
"select",
""
] |
I have created a sql query that updates certain tables taking a CSV file as the input.
I want my co-workers to be able to execute this query as easily as possible. At first, I thought a batch file using sqlcmd was the best solution.
The end product works on my computer, because I have SSMS installed, but no other com... | Why don't you create a C-Sharp or VB.Net program that executes the proc and distribute the program to your users? | Check SQLS\*Plus from www.memfix.com - works the best. | Alternatives to sqlcmd/best practice | [
"",
"sql",
"sql-server",
""
] |
Having a table with two columns, `PART_NUMBER` and `PART_TYPE`. A type can have many parts. The requirement is to find the unique combinations of the part numbers using a sql procedure. We are using Oracle as our DB. Sample data is as below:
```
PART_NO PART_TYPE
Part1 10
Part2 10
Part3... | Use a hierarchical query:
[SQL Fiddle](http://sqlfiddle.com/#!4/77585/2)
**Oracle 11g R2 Schema Setup**:
```
CREATE TABLE parts AS
SELECT 'Part1' AS PART_NO, 10 AS PART_TYPE FROM DUAL
UNION ALL SELECT 'Part2' AS PART_NO, 10 AS PART_TYPE FROM DUAL
UNION ALL SELECT 'Part3' AS PART_NO, 10 AS PART_TYPE FROM DU... | You don't need PL/SQL for this. Just SQL.
```
with TAB as (
select 'Part1' as PART_NO, 10 as PART_TYPE from dual union all
select 'Part2', 10 from dual union all
select 'Part3', 10 from dual union all
select 'Part4', 20 from dual union all
select 'Part5', 30 from dual union all
select 'Part6', 30 from dual... | SQL to find combinations within a column | [
"",
"sql",
"oracle",
""
] |
I have this table:
```
create table myTable (keyword text, category text, result text
, primary key (keyword,category));
insert into myTable values
('foo', 'A', '10'),
('bar', 'A', '200'),
('baz', 'A', '10'),
('Superman', 'B', '200'),
('Yoda', 'B', '10')... | What you seem to be looking for is called **relational division**. The task could be phrased as:
*Find results that have at least one row matching these conditions:*
`keyword LIKE '%a%' AND category = 'A'`
***and*** at least one row matching these other conditions:
`keyword LIKE '%Superman%' AND category = 'B'`
... | I think you can also take a look at the documentation [SIMILAR TO](http://www.postgresql.org/docs/8.4/static/functions-matching.html)
You can do something like this
```
SELECT * from myTable where keyword SIMILAR TO '%(oo|ba)%' and category SIMILAR TO '(A)';
``` | PostgreSQL multiple tuples selection in WHERE clause | [
"",
"sql",
"postgresql",
"where-clause",
"multiple-columns",
"relational-division",
""
] |
I have a problem to fiqure out the way to grap rows after last marked value from a table.
```
id | f_id | pi | typeId
1 | 1 | 10 | 1
2 | 2 | 24 | 2
3 | 1 | 34 | 3
4 | 1 | 56 | 2
5 | 1 | 12 | 1
6 | 2 | 34 | 1
7 ... | Consider the following
```
mysql> create table test (f_id int, pi int, typeid int,timestamp datetime);
Query OK, 0 rows affected (0.13 sec)
mysql> insert into test values
-> (1,10,1, date_add(now(),interval 1 minute)),
-> (2,24,2, date_add(now(),interval 2 minute)),
-> (1,34,3,date_add(now(),interval 3 m... | Try this. Myabe help you:
```
select id, max(f_id), max(pi), max(typeId)
from TABLE
where f_id=1 and typeID=1
group by id
order by max(f_id)
``` | mysql query for getting rows after last specific mark on the list | [
"",
"mysql",
"sql",
""
] |
I currently have a SQL query setup but I want it to ignore 0's in the `min_on_hand` column, and I can't seem to figure out why this doesn't work
```
SELECT
sku_master.sku,
sku_master.description,
sku_master.min_on_hand,
sku_master.max_on_hand,
x.total_qty_on_hand
FROM
[FCI].dbo.[sku_mast... | As others have mentioned in the comments, filtering on `min_on_hand` in the subquery has no effect - you'll still be returned the values in `sku_master`, but they just won't include any of the data from `x`.
If you move the check to the main query then you will not see any records where `min_on_hand` = 0
```
SELECT ... | I used this query. It returns an inventory summary, for all records where the minimum on hand quantity needs to exceed 0.
`/\* Left join sku\_master \*/
```
SELECT sku_master.sku, sku_master.description, sku_master.min_on_hand,
sku_master.max_on_hand,
location_inventor... | SQL with Left Join showing values that are zero | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I've stuck on this:
I need get **guid** based on minimum **ID** and remove all other duplicates (guid, ID).
ID is only unique field here.
```
+-----------------------------+------+-------------+
| guid | ID | post_parent |
+-----------------------------+------+-------------+
| 5.jpg ... | ```
select *
from wp_posts p,
(select min(ID) as id, post_parent
from wp_posts
group by post_parent) mins
where p.ID = mins.id and mins.post_parent = p.post_parent
``` | Find the row with the minimum id
```
SELECT *
FROM wp_posts p
WHERE NOT EXISTS ( SELECT 'a'
FROM wp_posts p2
WHERE p2.post_parent = p.post_parent
AND p2.id < p.id
)
``` | Return unique rows based on minimum id in mysql | [
"",
"mysql",
"sql",
""
] |
I have two tables in MySQL that hold users and another one holds there subscriptions. There are users may be sign but they do not subscribe. I use the following query to get the count of users that they have not any subscription:
```
SELECT COUNT(social_users.id) FROM social_users LEFT JOIN socials
ON social_users.id ... | try something like this
```
Select ( (SELECT COUNT(social_users.id) FROM social_users LEFT JOIN socials ON
social_users.id = socials.social_user_id WHERE socials.social_user_id
IS NULL) / (select count(social_users.id) FROM social_users))*100 as Percentage
``` | There should be no reason to query the same tables twice. If you take the user table and outer join with the social table, group by the user id, you can take a count of the subscriptions per user. Those with no subscription will have a count of zero.
Then just feed that into a query which essentially just counts the n... | SQL select percentage | [
"",
"mysql",
"sql",
""
] |
Let's say I have a this search query like this:
```
SELECT COUNT(id), date(created_at)
FROM entries
WHERE date(created_at) >= date(current_date - interval '1 week')
GROUP BY date(created_at)
```
As you know then for example I get a result back like this:
```
count | date
2 | 15.01.2014
1 | 13.01.2014
9 ... | ```
SELECT day, COALESCE(ct, 0) AS ct
FROM (SELECT now()::date - d AS day FROM generate_series (0, 6) d) d -- 6, not 7
LEFT JOIN (
SELECT created_at::date AS day, count(*) AS ct
FROM entries
WHERE created_at >= date_trunc('day', now()) - interval '6d'
GROUP BY 1
) e USING (day);
```
Use a [sarg... | Try this query:
```
with a as (select current_date - n as dt from generate_series(0, 6) as t(n)),
b as (select count(id) cnt, date(created_at) created_at
from entries
where date(created_at) >= date(current_date - interval '1 week')
group by date(created_at))
select coalesce(b.cnt,... | Get count of created entries for each day | [
"",
"sql",
"postgresql",
"aggregate-functions",
"generate-series",
""
] |
I have a table formatted like the following, we'll call it "Payments"
```
P_ID | P_PayNum | P_AmtPerc | P_Type
1 | 1 | 100 | FP1
2 | 1 | 50 | 2P1
3 | 2 | 50 | 2P1
4 | 1 | 25 | 4P1
5 | 2 | 0 | 4P1
6 | 3 | 0 | 4P1
7 ... | At sounds like you want to not just compute the missing payment percentages, but also to update the base table with them. In SQL Server, you can accomplish that this way:
```
UPDATE p
SET p.P_AmtPerc = r.remaining_perc / r.num_zero
FROM
payments p
INNER JOIN (
SELECT
P_Type,
100 - SUM(P_AmtPe... | Took me a moment to wrap my noodle around this one, you have different payment codes (at least for this example), but when all payments for a given code are made the percentage should equal out to 100%.
What you want is to find unpaid payments, where at least one payment has been made, and figure out how much is left ... | How to get remaining percentages for column? | [
"",
"sql",
"sql-server",
"database",
""
] |
I work in an Oracle instance that has hundreds of schemas and multiple developers. We have a development instance where developers can integrate their work before test or production.
We want to have source control for all the DDL run in this integrated development database. Currently this is done through a product Red... | We do this with help of a PL/SQL function, a python script and a shell script:
* The PL/SQL function can generate the DDL of a whole schema and returns this as CLOB
* The python script connects to the database, fetches the DDL and stores it in files
* The shell script runs the Source Control to add the modifications (... | Being in the database version control space for 5 years (as director of product management at [DBmaestro](http://www2.dbmaestro.com/l/11742/2014-12-31/2grnfp)) and having worked as a DBA for over two decades, I can tell you the simple fact that you cannot treat the database objects as you treat your Java, C# or other f... | How to automate source control with Oracle database | [
"",
"sql",
"plsql",
"oracle11g",
"oracle12c",
""
] |
Guys I have the following query:
```
select count(*) AS num_items
from desc_look
group by dept
```
This query returns the number of items in each department. However I can't get ONLY the department with the higher number of items.
I've been trying to use this to retrieve the name and id of the departme... | ```
select * from
(
select count(*) AS num_items
from desc_look
group by dept
order by count(*) desc
) tmp
WHERE ROWNUM = 1;
```
Also have a look on [howto limit the records in Oracle](https://stackoverflow.com/questions/470542/how-do-i-limit-the-number-of-rows-returned-by-an-oracle-query-after-orderin... | This version is basically the same as juergen's, but using an analytic function instead of an aggregate (`GROUP BY`) for counting:
```
SELECT t.dept, t.desc_up FROM
(SELECT dept, desc_up,
COUNT(*) over (partition BY dept) dept_count
FROM desc_look
ORDER BY dept_count DESC
) t
WHERE rownum = 1
```
If you'... | Query to get the "MAX COUNT" | [
"",
"sql",
"oracle",
""
] |
I need to update a column (type of `datetime`) in the top 1000 rows my table. However the catch is with each additional row I must increment the `GETDATE()` by 1 second... something like `DATEADD(ss,1,GETDATE())`
The only way I know how to do this is something like this:
```
UPDATE tablename
SET columnname = CASE ... | I don't know what your ID is like, and I'm assuming you have at least SQL Server 2008 or else ROW\_NUMBER() won't work.
Note: I did top 2 to show you that you that the top works. You can change it to top 1000 for your actual query.
```
DECLARE @table TABLE (ID int, columnName DATETIME);
INSERT INTO @table(ID)
VAL... | How about using `id` rather than a constant?
```
UPDATE tablename
SET columnname = DATEADD(second, id, GETDATE() )
WHERE id <= 1000;
```
If you want the first 1000 rows (by `id`), but the `id` has gaps or other problems, then you can use a `CTE`:
```
with toupdate as (
select t.*, row_number() over (orde... | Update table with new value for each row | [
"",
"sql",
"sql-server",
""
] |
I get the an error when I execute the query below. what I'm doing wrong?
Msg 512, Level 16, State 1, Line 3
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
```
select
so.name 'Table Name'
,so.id 'Table I... | I don't think your subquery is correct as it has no way of referencing your sysobjects aliased "so". Try this instead. Also I don't think you need such a long where clause.
```
select so.name [Table Name]
,so.id [Table ID]
,so.xtype
,sc.name [Column Name]
,sc.id [Colum... | ```
select so.name [Table Name]
,so.id [Table ID]
,so.xtype
,sc.name [Column Name]
,sc.id [Column ID]
,sf.constid
,sf.fkeyid [Object ID of the table with FOREIGN KEY]
,sf.rkeyid [Referenced Table ID]
,(select TOP 1 o.name
fro... | Please help me correct the syntax error | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I want to export one table to each csv file and name the csv file with timestamp. For example, if I have a table `t1`, after export, a csv file name t1.YYYYMMDDHHMISS.csv is generated. Here is my code:
```
create or replace procedure
T_to_CSV(Tname varchar2,Directory varchar2)
BEGIN
set colsep , -- separate col... | There are a few steps:
* create a [directory](http://www.adp-gmbh.ch/ora/sql/create_directory.html) using `CREATE DIRECTORY my\_dir as 'C:\dir';
* make sure that Oracle has read,write on the folder on the computer (best accomplished by creating it in the Oracle install folder)
* grant the user executing the procedure ... | Thanks kevin for sharing the procedure and it was very useful for me. I have customized the code:
1. To Add the column names in the output csv file which was not working earlier.
2. When i was passing the delimiter as parameter then it was adding the comma in the starting of every row(,1,2,3) which has been corrected.... | Export table to csv file by using procedure (csv name with timestamp) | [
"",
"sql",
"oracle",
"stored-procedures",
""
] |
I am trying to write a Query to find if a string contains part of the value in Column (Not to confuse with the query to find if a column contains part of a string).
Say for example I have a column in a table with values
> ABC,XYZ
If I give search string
> ABCDEFG
then I want the row with **ABC** to be displayed.
... | The answer would be "use LIKE".
See the documentation: <https://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html>
You can do `WHERE 'string' LIKE CONCAT(column , '%')`
Thus the query becomes:
```
select * from t1 where 'ABCDEFG' LIKE CONCAT(column1,'%');
```
If you need to match anywhere in the str... | ```
Select * from table where @param like '%' + col + '%'
``` | SQL - Query to find if a string contains part of the value in Column | [
"",
"mysql",
"sql",
"string",
"contains",
""
] |
Lets say I have a table like this:
```
id | peru | usa
1 20 10
2 5 100
3 1 5
```
How can I get the top values from `peru` and `usa` as well as the spefic ids. So that I get as result:
```
usa_id: 2 | usa: 100 | peru_id: 1 | peru: 20
```
Is this possible In **one** query? Or d... | You can do this with some subqueries and a cross join:
```
select
u.id usa_id,
u.usa,
p.id peru_id,
p.peru
from
(select id, usa from mytable where usa=(select max(usa) from mytable) order by id limit 1) u
cross join (select id, peru from mytable where peru=(select max(peru) from mytable) order ... | ```
SELECT
t1.id as peru_id, t1.peru
, t2.id as usa_id, t2.usa
FROM tab1 t1, tab1 t2
ORDER BY t1.peru desc, t2.usa desc
limit 1
```
<http://sqlfiddle.com/#!15/0c12f/6>
As basicly what this does is a simple carthesian product - I guess that performance WILL be poor for large datasets.
on the fiddle it took [196... | Get top values from two columns | [
"",
"sql",
"postgresql",
""
] |
I have two tables named `doctor` and `patient`
Here is my `doctor` table

Here is my `patient` table

First I wanted to retrieve list of doctor IDs together with the number of app... | You are doing `implicit join`
You need to use `left join` as
```
Select
d.doctor_id,
coalesce(count(p.patient_id),0) as `patient_count`
from doctor d
left join patient p on d.doctor_id=p.registered_with
group by d.doctor_id;
``` | you can do it with `right outer join`
```
Select d.doctor_id, count(p.patient_id)
from patient p right outer join doctor d
on d.doctor_id=p.registered_with
group by d.doctor_id;
``` | Retrieve records with no matching rows in joined table | [
"",
"mysql",
"sql",
"count",
"aggregate-functions",
""
] |
I need to implement a regular expression (as I understand) matching in PostgreSQL 8.4. It seems regular expression matching are only available in 9.0+.
My need is:
When I give an input `14.1` I need to get these results:
```
14.1.1
14.1.2
14.1.Z
...
```
But exclude:
```
14.1.1.1
14.1.1.K
14.1.Z.3.A
...
```
The pa... | [Regular expression matching](https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-POSIX-REGEXP) has been in Postgres practically for ever, at least since version 7.1. Use the [these operators](https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-POSIX-TABLE):
```
~ !~ ~* !~*
... | You can't do regex matching, but I believe you can do like operators so:
```
SELECT * FROM table WHERE version LIKE '14.1._';
```
Will match any row with a version of '14.1.' followed by a single character. This should match your examples. Note that this will not match just '14.1', if you needed this as well. You cou... | String matching in PostgreSQL | [
"",
"sql",
"regex",
"postgresql",
"pattern-matching",
"postgresql-8.4",
""
] |
I am very new to SQL and I'm attempting to work through some exercises and I am having some trouble with the following problem:
There is a database consisting of six tables:
1. Author(AUTHOR ID, AUTHOR NAME, AUTHOR FIRSTNAME)
2. Book(BOOK ID, ISBN, TITLE, EDITOR, EDITION DATE) which contains the list of books (ISBN a... | To start with the join you can use [this schema](http://www.codeproject.com/KB/database/Visual_SQL_Joins/Visual_SQL_JOINS_orig.jpg). | the answer of first question
```
SELECT
title
FROM book b, author a, written w
WHERE b.bookid = w.bookid AND a.authorid = w.authorid AND authorname = 'Ernest Hemingway';
``` | SQL Join and select | [
"",
"mysql",
"sql",
"sql-server",
""
] |
I have two columns having data like below.
Column1
AMC Standard, School
Column2
AMC Standard School.
In need to compare these two columns such that comparison is made for the words only and not for any additional, meaning from the above example Column1 and ColumnC are match but due to the Comma ",' and the perio... | you can replace the non comparable characters to empty string (in your case , and .)and then compare them. Something like this.
```
SELECT 1 WHERE REPLACE('AMC Standard, School',',','') = REPLACE('AMC Standard School.','.','')
```
Based on jarlh comments, You should (if possible) update the columns and remove the pun... | Try like this
```
DECLARE @column1 VARCHAR(100)='AMC Standard, School (Near to ABC Building)'
DECLARE @column2 VARCHAR(100)='AMC Standard, School (Opposite KFC)'
SELECT 'MATCHED' AS COLUMN_COMPARE
WHERE replace(replace(replace(@column1, ',', ''), '.', ''), substring(@column1, CHARINDEX('(', @column1), CHARINDEX(')',... | Is it possible to Compare two columns in Microsoft SQL server so that the comparison skips punctuation marks and other character like %, ' etc? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
My customer model has many videos and videos has many video activities.
I want to join on video activities to limit based off videos that belong to a customer who has a specific email domain.
This code will give me all the video activities belonging to customer with id 52, but since videos don't have customer email, ... | VideoActiviy has no relation with customer, you need to say that the customer is related to the video, then it's easier to use active record's [`#merge`](http://apidock.com/rails/ActiveRecord/SpawnMethods/merge) that doing a hash `where`
```
VideoActivity.joins(video: :customer).merge(Customer.where('some condition'))... | There are a bunch of ways to do this and all end up at about the same place, but using an explicit where statement will easily accomplish this goal.
```
VideoActivity.joins(:video).where("videos.customer_id = ?", 52)
``` | ActiveRecord multiple joins through association | [
"",
"sql",
"ruby-on-rails",
"join",
"activerecord",
""
] |
I'm trying to use this query, but I get an error
> Data mismatch in criteria
`Dat` is the `Date` column inside the MS Access database. I'm trying to select the sum of column named `Total` for every row named `Pro` between a date picked from the datepickers...
There are many posts regarding this, but my query is diff... | My edit seems to be cancelled, so here is:
```
Dim DTST As String
DTST = DateTimePicker1.Value.ToString("'#'yyyy'/'MM'/'dd'#'")
Dim DTEn As String
DTEn = DateTimePicker2.Value.ToString("'#'yyyy'/'MM'/'dd'#'")
Dim Query1 As String = "SELECT SUM(Total) FROM [T500] WHERE Pro =@Pro AND Dat BETWEEN " + DTST + " AND " + D... | The Dates are just additional parameters. One of the problems with the way you (and the other answers) are doing it is that you are converting perfectly good `DateTime` variables to string. MSAccess/OleDb will usually make sense of things, but it is unnecessary and allowing something else to interpret your intent is us... | 'Data criteria mismatch SQL' when using Dates | [
"",
"sql",
".net",
"vb.net",
"ms-access",
""
] |
I want to create a dynamic order by statement.
Its purpose is to read a table of daily schedule overrides (0 to \* records) and decide to use a global override or a store override, for selected day.
I thought of using a case clause like below but its not working as expected.
```
select * from schedule sdl
where day... | You seemed to be on the right track. You just have to generate a value for each row and make it meaningful to how you want them sorted.
```
select *
from schedule sdl
where day = 3
and (sdl.store_id = 23331 or sdl.store_id is null)
order by case when sdl.store_id is null and sdl.force then 0 --nulls in front... | yes it is possible, the link in the comment to your question shows a valid example but it looks like your issue is
"nulls first/last". These aren't valid postgres constructs. Your query should be like
```
select * from schedule sdl
where day = 3 and (sdl.store_id = 23331 or sdl.store_id is null)
order by
case when sdl... | ORDER BY with CASE clause | [
"",
"sql",
"postgresql",
""
] |
```
SELECT ai.auction_item_id, ai.starting_bid, b.bid_amount, i.*
FROM
auction_item as ai, //Table contains auction specific details about the item
item as i //Table contains general details about the item
INNER JOIN (
SELECT auction_item_id, bid_amount
FROM bid xb //Table co... | Try a sub-query. You geht a `0` if there a no entries in the bid-table because of the `coalesce`.
```
SELECT
ai.auction_item_id, ai.starting_bid,
Coalesce((SELECT max(xb.bid_amount)
FROM bid xb
WHERE xb.auction_item_id = ai.auction_item_id), 0) AS bid_amount,
i.*
FROM auction_... | Something like this?
```
SELECT ai.auction_item_id, ai.starting_bid, b.bid_amount, max(bid_amount)
FROM auction_item as ai
inner join bid b
on ai.auction_item_id = b.auction_item_id
inner join items i
on i.id = ai.listings_id
where ai.auction_id = 4
```
Adding your table schema to ... | Simple SQL inner join query - can't get working | [
"",
"mysql",
"sql",
""
] |
We have a table (T) with ~3 million rows and just two INT columns (ID1 and ID2), which together are set as a composite clustered key.
Early in a stored procedure we create a table variable (@A) which consists of a list of INTs.
The slow query is the following
```
SELECT T.ID1, T.ID2
FROM T
INNER JOIN @A AS A
ON A.... | Try creating an included (covering index):
```
create index idx_t_id1 on t(id1) include id2
```
This will allow your query to find everything it needs in the index pages and will not have to search in the main table. By the way is there a clustered index on table t? | You could try phrasing the query like this:
```
select a.id as id1,
(select t.id2
from t
where t.id1 = a.id
) as id2
from @a a;
```
This should scan `@a` and use the index for the lookup.
Two notes:
* If there can be multiple matches, use `cross apply` instead.
* If there could be no m... | How to reduce scan count on table with a composite index? | [
"",
"sql",
"sql-server",
""
] |
What is the reason that the following two queries give wildly different results?
```
MariaDB [mydatabase]> SELECT COUNT(DISTINCT(`price`)) FROM `products`; --Good
+--------------------------+
| COUNT(DISTINCT(`price`)) |
+--------------------------+
| 2059 |
+--------------------------+
1 row in se... | 'price' (apostrophes or quotes) is a string. It never changes, so the count is always 1.
`price` (backtics) refers to the column `price`. So it could be more than 1.
The inner parentheses are irrelevant. `COUNT(DISTINCT price)` is the same as your backtic version.
* `SELECT COUNT(*) FROM tbl WHERE ...` is a common w... | A straight single quote (') is used for [string literals](http://dev.mysql.com/doc/refman/5.6/en/string-literals.html) (along with straight double quote (")).
A backtick quote (`) is for [quoting identifiers](http://dev.mysql.com/doc/refman/5.7/en/identifiers.html).
Identifiers must be quoted if they match a reserved... | What makes the big difference between a backtick and an apostrophe? | [
"",
"mysql",
"sql",
"mariadb",
""
] |
This question is relevant to SQL Server. I have table with column called `gender` and 1 or 0 will be saved as integer. I want to know whether there is a method assign a label when I selecting it using `SELECT` statement.
For example
```
SELECT gender
FROM emp
```
AND if 1 occur `Male` AND 0 occur `Female` should be... | Use the CASE operator, i.e. CASE gender when 1 then 'Male' else 'Female' end.
Full select as follows:
```
SELECT gender,
CASE gender
when 1 then 'Male'
else 'Female'
end as gender_name
FROM emp
```
**UPD:**
Option with N/A to process all possible optios (if gender fi... | You can use `CASE`:
```
SELECT CASE WHEN gender = 1 THEN 'Male' ELSE 'Female' END AS gender
FROM emp
``` | Assign a value when for integer when USE select query | [
"",
"sql",
"sql-server",
"select",
""
] |
I've inherited a database table that has an nvarchar(MAX) column containing ASCII numbers. I need to convert and replace them with plain text. Is this possible using an SQL function?
From:
> 034 067 111 110 118 101 114 116 032 077 101 044 032 068 097 114 110 032 105 116 033 033 034
To:
> "Convert Me, Darn it!!"
Th... | ## Test Data
```
DECLARE @TABLE TABLE (ASCII_Col VARCHAR(1000))
INSERT INTO @TABLE VALUES
('034 067 111 110 118 101 114 116 032 077 101 044 032 068 097 114 110 032 105 116 033 033 034')
```
## Query
```
;WITH CTE AS(
SELECT CHAR(Split.a.value('.', 'VARCHAR(100)')) Char_Vals
FROM (SELECT
Cast ('<M>'... | A solution (without `split` function):
```
declare @input nvarchar(max);
declare @result nvarchar(max);
select @result = '';
select @input = '034 067 111 110 118 101 114 116 032 077 101 044 032 068 097 114 110 032 105 116 033 033 034';
--------------------------------
declare @index int;
declare @len int;
declare @ch... | Does SQL Server 2012 have a function or other way to convert a varchar column that contains ASCII to plain text? | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I want to add comments to my `SQL CLR` functions (as I do to other `SQL` objects I am creating or editing - functions, procedures and views). Unfortunately, I am not able to do this for the `SQL CLR` objects.
For example, the following code:
```
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ==================... | Basically, if it's a type not listed as having data stored in [`sys.sql_modules`](https://msdn.microsoft.com/en-us/library/ms175081.aspx) then the original text that created the object is not retained and so comments aren't retained. No CLR object stores such text. | While @Damien is correct as to *why* the comments are not saved, there is still a somewhat work-around to store comments: Extended Properties.
For example:
```
EXEC sys.sp_addextendedproperty @name = N'comments', @value = N'
-- ==========================================================================================... | How to add comments to SQL CLR function? | [
"",
"sql",
"t-sql",
"sql-server-2012",
"sqlclr",
""
] |
Accidently I noticed a bug-like behaviour in SSMS. I was querying from a table named Candidate with the below query.
```
select CandidateId, CandidateName from Candidate
where CandidateId='73415005-77C6-4D4B-9947-02D6B148E03F2'
```
I was copy-pasting the CandidateId which is a unique identifier, but somehow I added... | The top-level description is that the string is being converted to a unique identifier, so the last digit is ignored.
This logic is documented. First, unique identifiers have a slightly higher operator precedence than strings. The relevant part of the [documentation](https://msdn.microsoft.com/en-us/library/ms190309.a... | Because your column CandidateId is of type GUID the right (string) part of the condition gets converted to uniqueidentifier data type and truncated. You can see this in your execution plan. There will be a Scalar Operator(CONVERT\_IMPLICIT(uniqueidentifier,[@1],0)) in your index seek/scan operator. | Why is SQL Server giving me wrong output? | [
"",
"sql",
"sql-server",
"ssms",
""
] |
I'm attempting to calculate days of therapy by month from an oracle database. The (vastly simplified) data is as follows:
```
Therapies
+-----------+-----------+----------+
| Rx Number | StartDate | StopDate |
|-----------+-----------+----------|
| 1 | 12-29-14 | 1-10-15 |
| 2 ... | > How do I include overhanging therapies such that only the portion
> within the target time period is included?
```
select sum(
greatest(least(stopdate, date '2015-01-31' + 1)
- greatest(startdate, date '2015-01-01'), 0)) suma
from therapies
```
> How do I automatically generate these monthly summaries ... | Use a case statement to set the start date and stop date. Like the below:
`select sum(
Stopdate -
(case Startdate
when startdate < to_date(@YourBeginingDate) then To_date(@YourBeginingDate)
else startdate
end)
FROM therapies
WHERE stopdate > to_date(@YourBeginingDate)
AND StartDate < to_date(@YourEndingDate)` | Calculating days of therapy in a sql query | [
"",
"sql",
"oracle",
""
] |
```
Person
id | name
1 | Mark
2 | John
3 | Cathy
4 | Susan
5 | Rick
Property
id | property_type (A,B,C,D,E,F)
1 | A
1 | B
1 | C
2 | A
2 | A
2 | A
3 | C
4 | D
4 | E
4 | F
4 | A
3 | A
5 | A
5 | A
```
> Query would be - Find out peo... | You can use conditional aggregation in the `having` clause:
```
select pers.id,
pers.name
from person pers
join property prop
on pers.id = prop.id
group by pers.id,
pers.name
having sum(case when prop.property_type = 'A' then 1 else 0 end) >= 1
and sum(case when prop.proper... | ```
select p.* from
Person p join
(select id from Property
group by id having count(1)=1
and max(property_type)='A') t on p.id = t.id
```
Try this out.
I think your major problem is using `in` and `distinct` keyword | MYSQL query optimization - how to fetch unique column from right table of join | [
"",
"mysql",
"sql",
""
] |
I am working with a database that has multiple machines writing to it, each machine is identified by a column called ControllerID, so for example, One machine could have a controllerID of 20 and one could be 30 ext
What i want to do is for each machine get the elapsed time between the last reading and now. This is wha... | If have understood your goal correctly, you need something like
```
select
controllerID,
max(convert(datetime, ReaderTime)),
datediff(ss, max(dtReading), getdate())
from ReaderData
where CardID = 'FFFFFFF0 '
group by controllerID
```
This will give you information about last `ReaderTime` and difference f... | If you want to use OR in the way I think you do, you need to group the OR's in ()s as below.
```
SELECT TOP (2) controllerID, convert(Datetime,ReaderTime), DATEDIFF(SECOND,dtReading,GETDATE())
FROM ReaderData
WHERE (controllerID = '30' OR controllerID = '31' OR controllerID = '32... | sql server query with multiple where's | [
"",
"sql",
"sql-server",
""
] |
I have tried many combinations of the SQL functions; so as to have a 12 digit number including the dot character, including leading zeroes and decimal points.
For example:
for the number **121.22**, I want to format it to **000000121.22**
or for the number **12.2**, I want to format it to **000000012.20**
or for th... | If you're on SQL Server 2012 or later, you can use the format() function.
```
SELECT FORMAT(121.22, '000000000000.00')
SELECT FORMAT(12.2, '000000000000.00')
```
---
000000000121.22
---
000000000012.20 | for `ms sql versions not in (2012,2014)`:
```
cast(right('000000000',9-len(floor(the_number))) as varchar)
+ cast( cast(the_number as decimal(10,2))as varchar)
```
for `ms sql versions in (2012,2014)`:
```
format(the_number ,'000000000000.00')
``` | How to add Leading Zeroes and Decimal Points at the same time in SQL? | [
"",
"sql",
"sql-server",
""
] |
My query keeps returning an ORA-01427 error and I don't know how to resolve it.
```
update db1.CENSUS set (notes)
=
(
select notes
from db2.CENSUS cen
where db1.CENSUS.uid = cen.uid
)
where headcount_ind = 'Y' and capture_FY = '2015'
``` | You are getting the error because there exists more than one row in `db2.CENSUS` for at least value of `uid`. (There could be more.) You can figure out which values of `uid` are causing the issue by doing the following:
```
SELECT uid, COUNT(*)
FROM db2.census
GROUP BY uid
HAVING COUNT(*) > 1;
```
At that point yo... | quick and dirty is
```
update db1.CENSUS cen set cen.notes
=
(
select MAX(notes)
from db2.census census
where db1.DW_HRT_PERSONNEL_CENSUS.uid = census.uid
)
where cen.headcount_ind = 'Y' and cen.capture_FY = '2015'
```
But, this probably does not do what you want. Yo... | How can i resolve an ORA-01427 error (Single-row subquery returns more than one row)? | [
"",
"sql",
"oracle",
"plsql",
""
] |
I'm trying to write something like this:
```
case column_01
when column_01 = 5 AND column_02 = 'NO'
then value
else value_other
end
```
Is it somehow possible? | You have mixed the two different **syntax** for **CASE** expressions.
You could do it as:
```
CASE
WHEN column_01 = 5 AND column_02 = 'NO' THEN
value
ELSE
value_other
```
**1. simple\_case\_statement**
```
CASE [ expression ]
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN... | With case statements, you either check for the value of one column/variable and do your checks against that:
```
case column_01
when 1 then 'a'
when 2 then 'b'
...
else 'zzz'
end
```
or you check for conditions in each when clause:
```
case when column_01 = 5 and column_02 = 'NO' then value
when column_... | Is there possible to use in CASE statement in WHEN more columns? | [
"",
"sql",
"oracle",
"case",
""
] |
I've looked at a bunch of questions and solutions regarding many to many queries. I just can't seem to wrap my head around it. Maybe I'm not completely understanding the keywords in MySQL. But...
I have 3 tables. The first table is a list of peoples contact information. The second table is a list of mailing list categ... | ```
SELECT c.*
FROM contacts c
JOIN list_contact_joiner j on j.contact_id = c.id
JOIN list_type t on j.list_type_id = t.id
WHERE t.list_name = 'VIP''s'
```
If you already have the `id` of `VIP's` then you need to join only 2 tables
```
SELECT c.*
FROM contacts c
JOIN list_contact_joiner j on j.contact_id = c.id
WHERE... | Yes the join statement is not correct. It should be something as
```
select
c.name,
c.email,
lt.list_type
from list_contact_joiner lcj
join contacts c on c.id = lcj.contact_id
join list_type lt on lt.id = lcj.list_type_id
where
lt.id = ?
```
If you are looking for data with `$listID = 1;` then the place holder is
`... | MySQL Many to Many query confusion | [
"",
"mysql",
"sql",
""
] |
I neeed to develop a script that will capture all fields when one car is tied to more than one color.
If one car is tied to one color more than once, that needs to be captured only if that car is tied to additional colors.
If one car is tied to one color more than once and no other colors that does NOT need to be cap... | I would use either an `in` clause or a correlated `exists` clause. The latter should perform better than the former:
```
select id, car, color from test2
where car in (
select car
from test2
group by car
having count(distinct color) > 1
)
select id, car, color from test2 t
where exists (
select... | you need to perform a `count` twice:
```
with cte as
( select CAR,COLOR,count(*) cn
from test2
group by CAR,COLOR
)
select t.id,t.car,t.color
from test2 t
join(
select car,count(*)
from cte
group by CAR
having count(*)>1)q
on t.car=q.car
order by 1
```
*OUTPUT:*
```
ID CAR COLOR
1 5 10
... | select based on one field association with multiple values in another field | [
"",
"sql",
"oracle",
""
] |
I have 1000's of tables in SQL Server that have each been created from CSV files. The data in each table is all similar with each table representing a different day.
The problem I am having, is that there are lots of variations in the structure of the tables as well as the names of columns.
Some tables do however hav... | So if the tables are truly identical, then try this out. I actually use it to create your insert statements and it can drop the old tables if you want it to.
```
IF OBJECT_ID('dbo.table1') IS NOT NULL DROP TABLE dbo.table1;
IF OBJECT_ID('dbo.table2') IS NOT NULL DROP TABLE dbo.table2;
IF OBJECT_ID('dbo.table3') IS NOT... | You'll find a wealth of data in the informational view `INFORMATION_SCHEMA.COLUMNS`.
This will give you (among other things) the table name, order of columns, column names, and column definitions.
So, for example, you could do something like this:
```
;
-- Create a list of table pairs. If you have reason to believe... | Find tables that are copied / duplicate structure within database | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2014-express",
""
] |
I want run an `INSERT INTO table SELECT... FROM...`
The problem is that the table that I am inserting to has 5 columns, whereas the table I am selecting from has only 4. The 5th column needs to be set do a default value that I specify. How can I accomplish this? The query would be something like this (*note*: this is O... | Just add the default value to your select list.
```
INSERT INTO five_column_table
SELECT column_a, column_b, column_c, column_d, 'Default Value'
FROM four_column_table;
``` | Just select the default value in your `SELECT` list. It's always a good idea to explicitly list out columns so I do that here even though it's not strictly necessary.
```
INSERT INTO five_column_table( col1, col2, col3, col4, col5 )
SELECT col1, col2, col3, col4, 'Some Default'
FROM four_column_table
```
If you... | INSERT INTO using a query, and add a default value | [
"",
"sql",
"oracle",
"insert-into",
""
] |
Description of my problem:
For example I have a table "Item" and columns "id", "name", "color", but for some weird reason (please don't ask why - it wasn't me) in the "color" column there is an information about the item and it essentially should be called "description"
A lot of code in the project depends on it and si... | Short answer: no. Long answer: you could create insert and update triggers in Oracle that always keep those column in sync. But, the best thing to do would be to live with it, or rename it and fix your code. Having triggers and storing data in two columns just so your old code doesn't break, but lets your new code use ... | You can create an updatable view with properly named column.
See <https://msdn.microsoft.com/en-us/library/ms180800.aspx> | Oracle SQL: is it possible to reference a column by different name without renaming it | [
"",
"sql",
"oracle",
"tablecolumn",
""
] |
I am trying to create a table (shown below) for my final year project,
but I encountered SQL name conflict error. It seems the words 'User'
and 'role' are reserved by the SQL. Is there any way I can resolve the
issue, without renaming the words.
```
CREATE TABLE User
(
ID INT generated by default as identity PRIMA... | Put double quotes around User. In general it never hurts to quote all your identifiers. | Throw square brackets around their name (or any reserved word that you want as your column names).
[User]
or
[Role] | How to resolve SQL name conflict without renaming table attributes? | [
"",
"sql",
"database",
"derby",
""
] |
I am trying to work out the majority sub group of a group. For an example let's say my table looks like this:
```
+--------------------------------------------------+
| city | car_colour | car_type | qty |
+--------------------------------------------------+
| ----------------------------------------------... | ```
select distinct p.city, p.car_colour,sq.qty as qty
from ( select t.car_colour,t.city, sum(t.qty) as qty
from table1 t
group by t.car_colour,t.city
)p
join ( select q.city,max(q.qty) qty from
( select t.car_colour,t.city, sum(t.qty) as qt... | In case you use MS SQL:
```
DECLARE @t TABLE
(
city NVARCHAR(MAX) ,
color NVARCHAR(MAX) ,
qty INT
)
INSERT INTO @t
VALUES ( 'manchester', 'Red', 7 ),
( 'manchester', 'Red', 9 ),
( 'manchester', 'Blue', 8 ),
( 'london', 'Red', 2 ),
( 'london', 'Blue', 3 ),
... | sql group by sub group | [
"",
"sql",
""
] |
Suppose I have a table like this:
| subject | flag |
| --- | --- |
| this is a test | 2 |
`subject` is of type `text`, and `flag` is of type `int`. I would like to transform this table to something like this in Postgres:
| token | flag |
| --- | --- |
| this | 2 |
| is | 2 |
| a | 2 |
| test | 2 |
Is there an easy ... | Use a `LATERAL` join - with [`string_to_table()`](https://www.postgresql.org/docs/current/functions-string.html#id-1.5.8.10.7.2.2.35.1.1.1) in [Postgres 14+](https://www.postgresql.org/message-id/flat/CAFj8pRD8HOpjq2TqeTBhSo_QkzjLOhXzGCpKJ4nCs7Y9SQkuPw%40mail.gmail.com).
Minimal form:
```
SELECT token, flag
FROM t... | I think it's not necessary to use a join, just the `unnest()` function in conjunction with `string_to_array()` should do it:
```
SELECT unnest(string_to_array(subject, ' ')) as "token", flag FROM test;
token | flag
----... | Split column into multiple rows in Postgres | [
"",
"sql",
"postgresql",
"split",
"set-returning-functions",
""
] |
So I have a table like so . . .
```
Table A
| GROUP_NAME | USERID |
| group_A | user1 |
| group_A | user2 |
| group_B | user3 |
| group_A | user4 |
| group_B | user5 |
| group_C | user6 |
| group_B | user7 |
| group_C | user8 |
| group_C | user9 |
| group_A | user10 |
```
What I want is the total number of rows where... | If you want total number of users in the groups where count of users in that group is less than 5(say), use
```
SELECT group_name,
COUNT(userid)
FROM table_a
GROUP BY group_name
HAVING COUNT(userid) < 5;
```
For total number of distinct users, use
```
SELECT group_name,
COUNT(DISTINCT userid)
FROM... | One way is to use **COUNT() OVER()** analytic function.
For example,
**Setup**
```
SQL> CREATE TABLE t
2 (GROUP_NAME varchar2(7), USERID varchar2(6))
3 ;
Table created.
SQL>
SQL> INSERT ALL
2 INTO t (GROUP_NAME, USERID)
3 VALUES ('group_A', 'user1')
4 INTO t (GROUP_NAME, USERID)... | SQL total count of another count | [
"",
"sql",
"oracle",
""
] |
I've heard that it is faster to select colums manually ("col1, col2, col3, etc") instead of querying them all with "\*".
But what if I don't even want to query all columns of a table? Would it be faster to query, for Example, only "col1, col2" insteaf of "col1, col2, col3, col4"?
From my understanding SQL has to sear... | In general, reducing the number of columns in the `select` is a minor optimization. It means that less data is being returned from the database server to the application calling the server. Less data is usually faster.
Under most circumstances, this a minor improvement. There are some cases where the improvement can b... | You should try not to use `select *`.
* **Inefficiency in moving data to the consumer.** When you SELECT \*, you're often retrieving more columns from the database than your application really needs to function. This causes more data to move from the database server to the client, slowing access and increasing load on... | Is it faster to only query specific columns? | [
"",
"mysql",
"sql",
"performance",
"select",
""
] |
I have a table named `USER_OPTIONS`. If I query this table with:
```
SELECT * FROM USER_OPTIONS
```
I get the following result:

Now, I need to copy the same values (A,1), (B,2), (C,3), etc to the same table but change the `USER_ID` value.
The fina... | Just do a plain **INSERT INTO..SELECT**.
For example,
```
INSERT INTO user_options SELECT user_id + 1, code, code_value FROM user_options;
COMMIT;
SELECT * FROM user_options;
```
**TEST CASE**
```
SQL> SELECT * FROM user_options;
USER_ID C CODE_VALUE
---------- - ----------
2 A 1
2 ... | Try this
Insert into user\_options Select 3, code, code\_value from user\_options; | Copy data within a table and changing values | [
"",
"sql",
"oracle",
""
] |
I have a table like below, What I need that for any particular fund and up to any particular date logic will sum the amount value. Let say I need the sum for 3 dates as 01/28/2015,03/30/2015 and 04/01/2015. Then logic will check for up to first date how many records are there in table . If it found more than one record... | Based on your question, it seems that you want to select a set of dates, and then for each fund and selected date, get the sum of the fund amounts from the selected date to the previous selected date. Here is the result set I think you should be expecting:
```
Fund Date SumOfAmount
A 2015-02-28 550.00... | If i change your incorrect sample data to ...
```
CREATE TABLE TableName
([Id] int, [Fund] varchar(1), [Date] datetime, [Amount] int)
;
INSERT INTO TableName
([Id], [Fund], [Date], [Amount])
VALUES
(1, 'A', '2015-01-28 00:00:00', 250),
(2, 'A', '2015-01-28 00:00:00', 300),
(3, 'A', '2015-03-30 00:... | Summing up the records as per given conditions | [
"",
"sql",
"sql-server",
"vba",
"ms-access",
""
] |
I have a derived a table with 3 columns :
```
computerID
ScanDate
vulnerability level.
```
I want to group by **computerID** and get the vulnerability level of the latest **scanDate** WITHOUT having to add an inner join (the table is pretty big).
Is it possible? | if you want `Without join keyword`!!, you can do this :
```
select *
from your_table t
where (computerID, ScanDate) in
(
select computerID, max(ScanDate)
from your_table t1
where t1.computerID=t.computerID
)
```
[SQLFIDDLE DEMO](http://sqlfiddle.com/#!9/51bc1/2) | Sometimes, using `not exists` can work better than `group by`. Not always, but it is worth a try:
```
select d.*
from derived d
where not exists (select 1
from derived d2
where d2.computer = d.computer and d2.scandate > d.scandate
);
```
Alternatively, if you are a... | How to get extra information from the highest values from SQL table? | [
"",
"mysql",
"sql",
""
] |
A bit of a newbie question, probably an INNER JOIN with an "AS" statement, but I can't figure it out...
This is for a MYSQL based competition app. I want to select the "img\_title" for both img\_id1 and img\_id2. I can't figure out how to do it and still see which title is assigned to the associated \_id1 or \_id2.
M... | ```
select comp_id, img_id1, b.img_title as img_title1,
img_id2, b2.img_title as img_title2
from competitions a
left outer join on_deck b on b.img_id = a.img_id1
left outer join on_deck b2 on b2.img_id = a.img_id2
```
switch let outer join to inner join if you want to exclude rows in competitions that do not have tw... | You need a join for each image:
```
SELECT comp.comp_id, img1.img_id, img1.img_title, img2.img_id, img2.img_title
FROM competitions comp
INNER JOIN on_deck img1 ON img1.img_id = comp.img_id1
INNER JOIN on_deck img2 ON img2.img_id = comp.img_id2
```
`LEFT JOIN` if `img_id1` or `img_id2` can be `NULL`. | MySQL how to select what I need, most likely an inner join | [
"",
"mysql",
"sql",
"select",
""
] |
I have a table containing email addresses and account numbers (amongst other data).
I have removed the other data for simplification.
```
123456, joe@place.com
123457, phil@place.com
123456, jil@place.com
123456, jane@place.com
123458, john@place.com
```
Per the example above, most accounts have multiple email addre... | The inner query (`q`) will count how many distinct email addresses each account has. The outer query will then count how many accounts fall into each counting bucket (1, 2, 3, ...).
```
SELECT q.email_counter, COUNT(*) AS num_accounts
FROM (SELECT account_number,
COUNT(DISTINCT email_address) AS ... | You can use
```
select acc_no, count(*) from your_table group by acc_no
``` | How do I do a SQL query based on number of quantity | [
"",
"sql",
"group-by",
"sum",
""
] |
I have this:
```
Dr. LeBron Jordan
John Bon Jovi
```
I would like this:
```
Dr. Jordan
John Jovi
```
How do I come about it? I think it's regexp\_replace.
Thanks for looking.
Any help is much appreciated. | Here's a way using regexp\_replace as you mentioned, using several forms of a name for testing. More powerful than nested SUBSTR(), INSTR() but you need to get your head around regular expressions, which will allow you way more pattern matching power for more complex patterns once you learn it:
```
with tbl as (
sel... | If it is only two words, it will return that. ("Lebron Jordan" will return "Lebron Jordan")
If it is three words, it will take out the middle word ("Dr. LeBron Jordan" will return "Dr. Jordan")
```
DECLARE @firstSpace int = 0
DECLARE @secondSpace int = 0
DECLARE @string nvarchar(50) = 'Dr. Lebron Jordan'
SELECT @str... | Removing one word in a string (or between two white spaces) | [
"",
"sql",
"oracle",
"plsql",
"regexp-replace",
""
] |
How do I delete duplicates rows in Postgres 9 table, the rows are completely duplicates on every field AND there is no individual field that could be used as a unique key so I cant just `GROUP BY` columns and use a `NOT IN` statement.
I'm looking for a single SQL statement, not a solution that requires me to create te... | If you can afford to rewrite the whole table, this is probably the simplest approach:
```
WITH Deleted AS (
DELETE FROM discogs.releases_labels
RETURNING *
)
INSERT INTO discogs.releases_labels
SELECT DISTINCT * FROM Deleted
```
If you need to specifically target the duplicated records, you can make use of the in... | ### Single SQL statement
Here is a solution that deletes duplicates in place:
```
DELETE FROM releases_labels r
WHERE EXISTS (
SELECT 1
FROM releases_labels r1
WHERE r1 = r
AND r1.ctid < r.ctid
);
```
Since there is no unique key I am (ab)using the tuple ID `ctid` for the purpose. The physicall... | Delete duplicate rows from table with no unique key | [
"",
"sql",
"postgresql",
"duplicates",
""
] |
I am trying to select records where the record shares a field value with another record, but the query I am trying only returns one occurrence. For example, in this table:
```
COUNTRY LANGUAGE
Mexico Spanish
Portugal Portuguese
Russia Russian
Spain Spanish
Thailand Tha... | Found a solution:
```
SELECT * FROM `TABLE` WHERE `language` IN (
SELECT * GROUP BY `language` HAVING COUNT(primary_language) > 1
)
``` | You need to break this up into two steps. Get the list of languages in a sub-select, then get the rows:
SELECT \* FROM country\_language where language in (SELECT language FROM country\_language GROUP BY language HAVING COUNT(\*) > 1) | MySQL select where duplicates in field, not returning all records | [
"",
"mysql",
"sql",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.