Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I've always had this problem that went like this: * Have a slow SQL query that needs to be faster * Be confused why it's slow * Look at execution plan * Realize why it is slow * Know exactly what changes to the execution plan would likely result in a faster query * Attempt to formulate SQL query to get desired executi...
Because SQL is a fifth generation programming language (the only successful one I know of) - it's main feature is that it writes the code for you. It inspects the contents of the database and determines the best way to do things. That said, there are ways to manually change the execution plan on the fly via RECOMPILE....
SQL is a declarative language and its sole purpose is to help you write declarative code. You have to simply tell what you want to achieve. Then onwards it is the language's responsibility to figure out the best way to achieve it. Because the language still isn't that advanced, users often have to "know exactly what ch...
Why can't I just write an execution plan directly instead of SQL?
[ "", "sql", "performance", "" ]
I am new to Hive . I want to create the table in hive with the same columns as that of existing table plus some additional columns. I Know we can use something like this. ``` CREATE TABLE new_table_name AS SELECT * FROM old_table_name ``` This will create the table with same columns as that of old\_table\_name. But ...
Here is how you can achieve it: > Old table: ``` hive> describe departments; OK department_id int from deserializer department_name string from deserializer ``` > Create table: ``` create table ctas as select department_id, department_name, cast(null as in...
Simple way is to issue `ALTER TABLE` command to add more(additional) columns after the above `CREATE` statement.
create table in hive with additional columns
[ "", "sql", "hadoop", "hive", "bigdata", "" ]
I've come across a table design that immediately struck me as odd, but now that I've thought through it I can't seem to come up with a design that I'm really happy about. The existing design (simplified) is: ``` CREATE TABLE Accounts ( account_id INT NOT NULL, account_name VARCHAR(50) NOT NULL, CO...
## Relationship Cardinality Judging by your description, you need 1:N relationship, which means you do *not* need the junction table `Group_Accounts`. Just a simple FK from `Accounts` to `Groups` should do. ## Special Row The next question is how you pick one row at the N side (`Accounts`) to be "special". You can e...
It is definitely possible to get rid of Group\_Accounts. From your description, it seems each group has many accounts, but each account only has one group. So you would put the group\_id into the Accounts table as you suggest, and then put primary\_account\_id as a field in Groups.
Modeling a 1:Many relationship with an attribute
[ "", "sql", "database-design", "" ]
The data in T1 and T2 is present for multiple rows on multiple dates, i wrote these sql to get below data sets. Table T1 is result of below sql: ``` select SYS_ID, SYS_NM FROM T1 WHERE dt = '30-NOV-2015' group by SYS_ID, SYS_NM order by 1,2; T1 SYS_ID SYS_NM 4 MPC 4 MHL 6 FR ...
You are close. Try this: ``` SELECT * FROM T1 WHERE NOT EXISTS (SELECT * FROM T2 WHERE T2.SYS_ID = T1.SYS_ID AND T2.SYS_NM = T1.SYS_NM) order by 1, 2; ``` UPDATE: I am guessing that you are seeing duplicate rows in the result. If so, adding "DISTINCT" will correct that. I also noticed the answer that I previ...
You could go for the usual equality comparison between all columns of both tables, inverted with the "not" operator. *What I mean, is, just go for a `SELECT` for the case that you want to retrieve rows that are same, inverted with a "not" operator.*
How to get the difference (data) in data between two independent tables - using sql
[ "", "mysql", "sql", "database", "" ]
I have the following table: ``` tableA +-----------+--------+ | tableA_id | code | +-----------+--------+ | 1 | code A | | 2 | code B | | 3 | code A | | 3 | code C | | 3 | code B | | 4 | code A | | 4 | code C | | 4 | code B | | 5 | code A | | ...
Using condtitional aggregation(portable between different dialects): ``` SELECT tableA_id, MAX(CASE WHEN code ='code A' THEN 'yes' END) AS "code A", MAX(CASE WHEN code ='code B' THEN 'yes' END) AS "code B", MAX(CASE WHEN code ='code C' THEN 'yes' END) AS "code C" FROM tableA GROUP BY tableA_id; ``...
You Need something like this in SQL Syntax ``` Select * From Table1 pivot ( Aggregate function For Column Name in ([CodeA], [CodeB] , [CodeC])) as PivotTable ```
SQL convert row values to column headers
[ "", "sql", "pivot", "crosstab", "" ]
Using `SQLite`, I'd like to split a string in the following way. Input string: ``` C:\Users\fidel\Desktop\Temp ``` and have the query return these **rows**: ``` C:\ C:\Users\ C:\Users\fidel\ C:\Users\fidel\Desktop\ C:\Users\fidel\Desktop\Temp ``` In other words, I'd like to split a file path into its constituent p...
This is possible with a recursive [common table expression](http://www.sqlite.org/lang_with.html): ``` WITH RECURSIVE split(s, last, rest) AS ( VALUES('', '', 'C:\Users\fidel\Desktop\Temp') UNION ALL SELECT s || substr(rest, 1, 1), substr(rest, 1, 1), substr(rest, 2) FROM split WHERE rest <...
Recursive CTE: ``` WITH RECURSIVE cte(org, part, rest, pos) AS ( VALUES('C:\Users\fidel\Desktop\Temp', '','C:\Users\fidel\Desktop\Temp'|| '\', 0) UNION ALL SELECT org, SUBSTR(org,1, pos + INSTR(rest, '\')), SUBSTR(rest, INSTR(rest, '\')+1), pos + INSTR(rest, '\') FROM cte WHERE INS...
Split a string into rows using pure SQLite
[ "", "sql", "string", "sqlite", "split", "" ]
I've only just began to run explain on my queries and see that the type is All and I'm using filesort. I'm not sure how to optimise even the simplest of queries, if anyone could provide guidance on the following query which just retrieves users and orders by their first name primarily and second name secondarily: ```...
Add index (Blocked, FName, SName) And change where to `Blocked = 0`, if it is possible
If you want optimize this query you could create an index on the field in where condition ``` CREATE INDEX id_users_blocked ON users (Blocked) ; ``` the optimization depend by the number of users withBlocked <> 1 If these are few don't aspect particolar improvement .. but in explain you don't shoudl see All. You ca...
optimise simple mysql query with order by on two columns
[ "", "mysql", "sql", "select", "sql-order-by", "query-optimization", "" ]
I have a table like this.. ``` Priority | Amount | Case P1 | 100 | 1 P1 | 200 | 2 P1 | 300 | 1 P3 | 400 | 3 ``` I want to first order this by `Priority` and `Amount` (Descending) and then `Case`, to look like this. ``` Priority | Amount | Case P1 | 300 | 1 P1 | 100 ...
You need to use a windowed aggregate to find the *highest* amount within each `Case`, and then use *that* for sorting: ``` declare @t table ([Priority] varchar(19) not null,Amount int not null, [Case] int not null) insert into @t ([Priority],Amount,[Case]) values ('P1',100,1), ('P1',200,2), ('P1',300,1), ('P1',200,0),...
``` CREATE TABLE SHANKATABLE (PRIORITY VARCHAR(2), AMOUNT INT, [CASE] INT) INSERT INTO SHANKATABLE VALUES('P1', 100 , 1) INSERT INTO SHANKATABLE VALUES ('P1', 200 , 2) INSERT INTO SHANKATABLE VALUES ('P1', 300 , 1) INSERT INTO SHANKATABLE VALUES ('P3', 400 , 3) ``` To achieve first result simply use below quer...
ORDER BY or GROUP BY based on three columns in SQL Server
[ "", "sql", "sql-server", "group-by", "sql-order-by", "" ]
i have table COBA with 3 fields, they are NOMER, NAMA, KETERANGAN. in table there are exist data like this: [![table COBA](https://i.stack.imgur.com/Ki3uS.png)](https://i.stack.imgur.com/Ki3uS.png) i wanna insert another values to that table, but how can i prevent duplicate insert query data in oracle? i have tried u...
If you dont wanna use Unique constraint, you can you `left join` while inserting to check if the `nomer` exists in target or not like below. By this method you will not get error even if the record already exists in your table. It will just be skipped. ``` insert into coba (select s.nomer,s.nama,s.ket from (selec...
Use a unique constraint: ``` ALTER TABLE COBA ADD CONSTRAINT uni_c UNIQUE (NOMER, NAMA, KETERANGAN) ```
Prevent Duplicate Insert Data in Oracle
[ "", "sql", "oracle11g", "" ]
I am trying to write a query to get all nodes with their ancestors. The database stores a tree (nodes and their children/parents). I know that connect by can give all ancestors, and when coupled with the start with clause you can get all ancestors of a single node. Here is a quick example to illustrate what I am going...
I don't think "start with" does what you intend it to do. That's going to restrict your root rows, which is why you get a limited result set. You also want CONNECT\_BY\_ROOT to get not just the child\_id, but the child\_id of the root rows. Disclaimer: I am not an oracle guru, I just had some time. The SYS\_CONNECT\_B...
Use `CONNECT_BY_ROOT` operator: ``` WITH edges (child_id, parent_id) AS ( SELECT 2, 1 FROM DUAL UNION ALL SELECT 3, 2 FROM DUAL UNION ALL SELECT 4, 2 FROM DUAL UNION ALL SELECT 5, 4 FROM DUAL ) SELECT child_id, CONNECT_BY_ROOT parent_id parent_id FROM edges CONNECT BY PRIOR child_id = paren...
Oracle connect by to find child, ancestor pairs
[ "", "sql", "oracle", "connect-by", "" ]
I have this query in SQL Server: ``` select column from table_53; ``` Now, I want to get this 53 from another table, so what I want to do is something like this: ``` select column from table_(select id from table2); ``` Is there any way to do this in SQL Server?
**You need dynamic sql query here.** ``` declare @sqlQuery = 'select column from table_('; set @sqlQuery = @sqlQuery + 'select id from table2)'; EXEC (@sqlQuery) ``` Note :- One of cons of using dynamic sql query is sql injection. I would suggest to have better table structure or try to used parameterized query.
This is definitely not the way SQL thinks and works. Maybe your suggested approach can be mimicked by way of writing stored procedures in which you create SQL-statements which are then evaluated. However, this will not be very efficient. A better approach would be to store the values of all your individual separate ta...
SQL Server - select into from statement?
[ "", "sql", "sql-server", "" ]
I have two tables - player, which stores players data, and similar table team. I want to select from these two tables name and surname of player and name of team to which one he belongs. I used this query: ``` SELECT player.name, player.surname, team.name AS teamname FROM player, team WHERE player.id_player=team....
I think you need to join on the team id. I am guessing something similar to this will work: ``` SELECT p.name, p.surname, t.name AS teamname FROM player p JOIN team t ON p.team_id_team = t.id_team ; ----------^ Note the change here ``` Also: * Learn proper `JOIN` syntax. Simple rule: *Never* use commas in...
You must use JOIN to "connect" the tables. With "WHERE" you only can exclude rows; ``` SELECT p.name, p.surname, t.name AS teamname FROM player p LEFT JOIN team t ON p.id_player = t.id_team ; ```
Selecting rows from two tables MySql
[ "", "mysql", "sql", "" ]
Table A is an inventory of items imported from a CSV file. The spreadsheet included a column for location of inventory items (i.e., toothbrush, bathroom). Table B is a list of all the distinct locations from Table A. I now want to update table A with the ID from Table B, in a new column in Table A set up as a foreign...
When you are doing a `SELECT`, `INSERT`, `DELETE`, `UPDATE` operation on a particular table in `WHERE` clause the left had side is always your reference of the target table. So in this case `imported_data_copy.location` is your target column and should be on left hand side. This is a bit different from a logical or mat...
The problem turned out to be that I did not include the `locations` table in the UPDATE clause. The correct syntax turned out to be: ``` UPDATE imported_data_copy,locations SET imported_data_copy.location_id=locations.id WHERE imported_data_copy.location LIKE locations.as_entered; ``` Glad I asked here, though, beca...
How To Populate Foreign Key by Comparing Columns in Two Tables
[ "", "mysql", "sql", "database", "" ]
I want to group values and sum them up by a category value - or none. For example, I have the following table: ``` +-------+----------+ | value | category | +-------+----------+ | 99 | A | | 42 | A | | 76 | [NULL] | | 66 | B | | 10 | C | | 13 | [NULL] | | 27 | ...
First calculate the sum of nulls then add it to each group: ``` DECLARE @t TABLE ( value INT , category CHAR(1) ) INSERT INTO @t VALUES ( 99, 'A' ), ( 42, 'A' ), ( 76, NULL ), ( 66, 'B' ), ( 10, 'C' ), ( 13, NULL ), ( 27, 'C' ) ;with cte as(select...
If you want to add the `NULL` values to all the groups, then do something like: ``` with cte as ( select category, sum(value) as sumv from t group by category ) select cte.category, (cte.sumv + (case when category is not null then coalesce(ctenull.sumv) else 0 end) ) as sum...
GROUP BY with summing null values to every group
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I am using a SQL Server 2016 database and in my stored procedure I want to compare two dates. I get one date parameter as string in 'dd-MM-yyyy' format. ``` @stringdate = '28-12-1990' // I get date in this format ``` I want to convert this to date format and compare with a database column which is of type `datetim...
You need to use **CAST()** function to convert to date format. **Try this Code:** ``` CAST(dbdatetimecolumnname AS date) = (CAST(RIGHT(@stringdate,4) + '-' + LEFT(RIGHT(@stringdate,7),2) + '-' + LEFT(@stringdate,2) AS DATE)) ``` **Right()** & **Left()** functions are used rearrange your string date format to db date...
Since you're on SQL Server **2016**, you could use the `PARSE` function and define the culture needed to successfully parse this string. Something like ``` DECLARE @stringdate VARCHAR(20) = '28-12-1990'; DECLARE @parseddate DATETIME2(3); SELECT @parseddate = PARSE(@stringdate AS DATE USING 'de'); SELECT @parseddate ...
SQL Server Date Comparison from string to datetime
[ "", "sql", "sql-server", "sql-server-2016", "" ]
I am having an issue, I am new to SQL query work, but I have a query that runs and display employees and all their addresses history, but I have found that staff have been missing checking off the indicator for if the employee has mailing address. The addresses are stored in a table that has a reference to the employee...
This will get you a list of employees that do not have a mailing address. Note that we start with all employees, outer join to the addresses, but constrain to not only match the employee, but also to be of the desired type of address. The `WHERE` clause then removes records from the resulting recordset where there is a...
This should return your employee #100 with all the addresses stored, even if employee has not address (any type). ``` select e.name, ad.type_add_desc, a.street from employee e left outer join address a on e.refid = a.refid left outer join addelement ad on a.type_add_id = ad.type_add_id where e.refid = 100 order by e.n...
SQL Query Display records only when value is missing
[ "", "sql", "" ]
I have a table with millions of records and I've been running this query once a day for over 500 days and just recently it stopped working. The query looks as follows: ``` SELECT id FROM table ORDER BY column1 desc, column2 desc, column3 desc LIMIT 522, 1 ``` This returns an empty result set. However, if I change th...
Not sure exactly how it occurred, but after optimizing the table it began working again...
I can only imagine some sort of time-out or error occurring. The `order by` and `limit` should be returning rows, if they are there. First, check to see if you are getting an error. If you are calling from an application, this requires checking the error status. For a time-out, you might consider adding an index on `...
Unexpected empty result set using limit with order by
[ "", "mysql", "sql", "" ]
I have a requirement to filter a specific row while doing summation. Table structure and data as below. [![enter image description here](https://i.stack.imgur.com/14uyR.png)](https://i.stack.imgur.com/14uyR.png) I want to SUM of `[Gain/Lost]` column value for all rows except the row `WHERE [Reason] = 'Order Placed' AN...
You described your conditions pretty well in English - now you just need to write the same thing in SQL: ``` SELECT SUM([Gain/Lost] FROM mytable WHERE NOT ([Reason] = 'Order Placed' AND [No Of Month Old] = 1) ```
``` select userid, sum([Gain/Lost]) from tablename where [Reason] <> 'Order Placed' or [No Of Month Old] <> 1 group by userid ```
Conditional WHERE condition SQL script
[ "", "sql", "sql-server", "select", "sum", "where-clause", "" ]
In my application, I have a table that identifies resources (i.e. pictures) by their id. Said resources have also been "tagged" (field1). i.e. Picture 3 in the table below is tagged with both 'A' and 'B'. Whereas Picture 1 is tagged with only 'A' and Picture 2 is tagged with only 'B'. Here is my "tagging" table: ``` ...
here are two methods: exists subclause: ``` SELECT id from pictures as pictures1 WHERE field1 = 'B' and not exists ( select * from pictures as picutures2 where pictures2.id = pictures1.id and pictures2.field1 = 'A'); ``` left join: ``` Select pictures1.id from pictures as pictures1 left jo...
You started well with your request. Just unselect rows where field1 is A. : ``` SELECT id from pictures WHERE field1 = 'B' AND id NOT IN( SELECT id from pictures WHERE field1 = 'A' ); ```
MySQL: Return all rows with same ID but filter by a different field
[ "", "mysql", "sql", "" ]
With this query ``` SELECT product, customer, sum(sales) as topSales FROM invoices WHERE product in (//lots of product id's here) GROUP BY product, customer ORDER BY topSales DESC ``` I get a result set containing all buyers for a product, in order of sales descending. ``` PRODUCT CUSTOM...
You can do this using window funtions: ``` SELECT * FROM (SELECT product, customer, sum(sales) as topSales, ROW_NUMBER() OVER (PARTITION BY product ORDER BY SUM(sales) DESC) as seqnum FROM invoices WHERE product in(//lots of product id's here) GROUP BY product, customer ) pc WHERE ...
From: <https://dba.stackexchange.com/questions/1002/how-to-get-the-max-row> (see link for more examples of how you can get your top row) ``` --ranking + derived table SELECT C.* FROM (SELECT ROW_NUMBER() OVER (PARTITION BY product ORDER BY topSales ) AS topBuyer, product, customer, sum(sales) as topSales FRO...
Select distinct on one column, returning multiple rows and columns
[ "", "sql", "sql-server", "" ]
I have a table that I need to query to obtain the most recent record in which the description contains certain data. The table columns contain (in part) the following: ``` +-----------+------------+-------------------+ | AccountID | Date | Description | +-----------+------------+-------------------+ | 1...
In your query nothing guarantees that mysql will select those description fields that have the max(date) value. Actually, your version is against the mysql standard and works in mysql under certain configuration settings only. The solution is to get the max dates by account ids where the description matches the criter...
Perhaps your old MySQL can handle this version. It combines the `AccountID` and `Date` values into a single result that works with `in`. ``` select p.Account, p.Date, p.Description from products p where p.AccountID in (125060, 125687, 139554) and p.Description like '%Apples%' and concat(cast(p....
MySQL Query: Select latest record where column contains certain criteria
[ "", "mysql", "sql", "group-by", "subquery", "" ]
Suppose I have the following tables: ``` CREATE TABLE parents ( id int primary key ); CREATE TABLE children ( parent_id int, --id from parents day int, status bool, } INSERT INTO parents (id) VALUES (1); INSERT INTO children (parent_id, day, status) VALUES (1, 1, TRUE); INSERT INTO children (parent_...
You don't need to join to parents. ``` SELECT parent_id FROM children GROUP BY parent_id HAVING MIN(Status) = 'TRUE' AND MAX(Status) = 'TRUE' ``` No other Status besides TRUE.
``` SELECT id FROM parent P WHERE (P.id) IN (SELECT c.parent_id FROM children c WHERE c.status = TRUE) ``` This will give you the desired result.
Select rows where field in joining table is same in every row
[ "", "mysql", "sql", "" ]
First, I know this has been addressed before - I've done my research and as you'll see below, I have tried multiple versions to get this to work. I am trying to set up a query in which a variable can be set and the query uses that variable. Here's my code: ``` -- Set to the category you want to check DECLARE @validat...
This is what your first attempt is generating.. ``` SELECT DISTINCT Category FROM MasterFiles.dbo.xref WHERE Category = 'D' AND (new_value NOT IN (SELECT 'M' FROM M) AND old_value NOT LIKE '%New%' OR (new_value IS NULL OR new_value = '') ) ) -- extra ``` This has an ex...
First test, print the query variable ( @vQuery ), copy and paste it in a new query window and execute it. You're gonna identify where the error is exactly. I think you need to do this, just like you do with your @validationTable: ``` DECLARE @vQuery nvarchar SET @vQuery = ' SELECT DISTINCT Category FROM MasterFiles.d...
SQL Server - Table name as variable in query
[ "", "sql", "sql-server", "sql-server-2008", "variables", "sql-server-2012", "" ]
I am currently learning PL/SQL so i am still a newbie. Assume that you have a production database, which you connect to using Oracle SQL developer. You have ONLY READ privilges to that databases. Therefore you cannot create or edit any tables. My question is, if i have a big list of IDs, which i have to join with a ta...
Use a collection ``` VARIABLE cursor REFCURSOR; DECLARE your_collection SYS.ODCIVARCHAR2LIST := SYS.ODCIVARCHAR2LIST(); BEGIN your_collection.EXTEND( 10000 ); FOR i IN 1 .. 10000 LOOP -- Populate the collection. your_collection(i) := DBMS_RANDOM.STRING( 'x', 20 ); END LOOP; OPEN :cursor FOR SELE...
Your friendly dba can map a directory for you to use, that will let you plop your file in there, and treat it as a table. Then basically you join with the file-as-table. Ask your DBA about EXTERNAL\_TABLES.
How to load a large number of strings to match with oracle database?
[ "", "sql", "oracle", "oracle-sqldeveloper", "" ]
I have tables A, B, C. Table A is linked to B, and table A is linked to C. I want to join the 3 tables and find the sum of B.cost and the sum of C.clicks. However, it is not giving me the expected value, and when I select everything without the group by, it is showing duplicate rows. I am expecting the row values from ...
I found this ([MySQL joining tables group by sum issue](https://stackoverflow.com/questions/12026182/mysql-joining-tables-group-by-sum-issue)) and created a query like this ``` select * from A join (select B.a_id, sum(B.cost) as cost from B group by B.a_id) B on A.id = B.a_id left join (select C.keyword_id, sum...
If I understand the logic correctly, the problem is the Cartesian product caused by the two joins. Your query is a bit hard to follow, but I think the intent is better handled with correlated subqueries: ``` select k.*, (select sum(cost) from ad_group_keyword_network n where n.event_date >= '201...
How can I join 3 tables and calculate the correct sum of fields from 2 tables, without duplicate rows?
[ "", "sql", "postgresql", "" ]
According to the [`UPDATE` documentation](https://msdn.microsoft.com/en-us/library/ms177523.aspx#Anchor_8), an `UPDATE` always acquires an exclusive lock on the whole table. However, I am wondering if the exclusive lock is acquired before the rows to be updated are determined or only just before the actual update. My ...
No, at least the nested select statement can be processed before the update is started and locks are acquired. To make sure that no other query interferes with this update it is required to set the transaction isolation level to `SERIALIZABLE`. This article (and the series it is part of) explains very well the subtlet...
If you want exactly one task with static = active, then set up the table to ensure this is true. Use a filtered unique index: ``` create unique index unq_tasks_status_filter_active on tasks(status) where status = 'Active'; ``` A second concurrent `update` might fail, but you will be ensured of uniqueness. Your ap...
Is a transaction that only updates a single table always isolated?
[ "", "sql", "sql-server", "transaction-isolation", "" ]
I would like to return boolean value if the record exists. The below query works fine for single table. ``` SELECT CASE WHEN MAX(componentid) IS NULL THEN 'NO' ELSE 'YES' END table3 FROM table3 WHERE componentid = 'GetAccountBalance'; ``` I have tried the same for 3 tables using JOIN but I couldn't achieve the expect...
You should phrase this as `exists`: ``` select (case when exists (select 1 from table1 where componentid = 'GetAccountBalance') then 'YES' else 'NO' end) as flagTable1, (case when exists (select 1 from table2 where componentid = 'GetAccountBalance') then 'YES' else 'NO' ...
You want an outer join on all three tables. You also need to include a condition that checks the presence of the value in all three tables: ``` select coalesce(a.componentid, b.componentid, c.componentid) as componentid, case when a.componentid is null then 'no' else 'yes' end as in_table1, case when b.c...
How to return boolean if record exists for multiple tables
[ "", "sql", "oracle", "" ]
I have imported a price list from a csv to my SQL Server database. That has worked fine. But now some weird stuff. Table is named `PRICE` which includes a column (and some more) `Endprice` and a total of 761 rows. All datatypes are `varchar(50)`. ``` SELECT MAX(Endprice) FROM PRICE ``` When I want this simple SQL st...
This is because your column is a varchar, so it is determining the min or max based on characters. The column should be a decimal or money type, so it sorts by the value of your number (instead of an alphabetic sort like you are getting now). Alphabetic sort: 9 is more than 1, thus 98.39 is the max.
The reason is because price is a `varchar()`. Here are two solutions: ``` order by len(price), price ``` This works assuming that all the price values have the same structure. Or: ``` order by cast(price as float) ``` If you could have non-numeric values (always a danger when storing numbers in the wrong data typ...
SQL Server : aggregate function doesn't work?
[ "", "sql", "sql-server", "database", "sql-server-2008", "aggregate-functions", "" ]
I need to figure out which datatype to use for **states**. Should it be `SET` or `VARCHAR` or anything else? ``` CREATE TABLE actors( state SET('USA','Germany','....) ) ``` alternatively ``` CREATE TABLE actors( state VARCHAR(30) ) ```
Assuming there's going to be tens or over hundred of the countries, it's best to use separate table. ``` CREATE TABLE states( state_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) ); ``` *It's also recommended to use foreign key on the state\_id so if you want to delete a state from your database, it...
SET is a compound datatype containing values from predefined set of possible values. If table contains such a data then according to relational databases theory it is not in 1NF. So it is only few special cases where this approach is reasonable. In most cases I suggest using separate table for countries like in example...
MYSQL|Datatype for states
[ "", "mysql", "sql", "database", "sqldatatypes", "states", "" ]
I need to join two tables in SQL. There are no common fields. But the one table have a field with the value `krin1001` and I need it to be joined with the row in the other table where the value is `1001`. The idea behind the joining is i have multiple customers, but in the one table there customer id is 'krin1001' 'kr...
You need to use substring: ``` ON SUBSTRING(TableA.Field, 5, 4) = TableB.Field ``` Or Right: ``` ON RIGHT(TableA.Field, 4) = TableB.Field ```
You can also try to use `CHARINDEX` function for join operation. If value from `table1` contains value from `table2` row will be included in result set. ``` ;WITH table1 AS( SELECT 'krin1001' AS val UNION ALL SELECT 'xxx' UNION ALL SELECT 'xyz123' ), table2 AS( SELECT '1001' AS val UNION AL...
SQL Join 2 tables with almost same field
[ "", "mysql", "sql", "" ]
I have this query in postgresql: ``` select * from A s join B m on (s.id=m.id) where m.key=4 and s.ran=some_input_from_user ``` This gives me all the rows that I need to update. I want to set `A.value` to be `90` for all these rows. It doesn't look like a standart update query if I do... ``` Update A set value=90...
This is the basic update syntax for PostgreSQL where you are updating based on a join to another table: ``` update A s set value = 90 from B m where s.id = m.id and m.key = 4 and s.ran = some_input_from_user ``` The trick is you never use the alias in the lvalue for the `set` commands. In other words, `value ...
Here is the query: ``` update a set value = 90 where exists ( select 1 from b where a.id = b.id and b.key=4 and a.ran=some_input_from_user); ``` The above query will eliminate the requirement of reading table a twice. Also you can use this query: ``` update a set value = 90 where a.id...
update multiple rows with joins
[ "", "sql", "postgresql", "" ]
This question has been asked previously and been well answered for MySQL specifically, however I'd very much appreciate your guys' help in translating this for SQL Server. The prior posts are closed and I didn't want to reopen them as they're quite old. Below is the dataset to query, and the required output of the que...
By using a CTE you would be able to get the data ordered, and then select the previous record. ``` WITH PREVCTE AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY SN ORDER BY MyDate) [RowNum] FROM @myTable ) SELECT A.SN, A.MyDate, A.[Value], A.[Value] - COALESCE(B.[Value], A.[Value]) [Co...
My previous solution had calculated running totals. After shawnt00's comment and looking back at the example that you've provided I see that's not the case. This should make a solution much easier. I believe that the following will work for SQL 2008, although I don't have a 2008 box handy at the moment to test it. ```...
Subtracting Previous Value by Prior Group - SQL Server
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have this query which does get the results I require but is incredibly slow and surely there must be a better way of doing this as I would need to run this regularly. Each where clause has two variables which will always be the same number but I need to use this with 50+ BigIDs, the example shows 3 but I would do it...
One method is a correlated subquery: ``` SELECT t1.BigID, count(t1.LittleID) FROM Table1 t1 WHERE t1.BigID IN (1, 2, 3) and t1.LittleID not in (SELECT t2.LittleID FROM Table2 t2 WHERE t2.BigID = t1.BigId ) GROUP BY t1.Bi...
``` SELECT t1.BigID, COUNT(t1.LittleID) FROM Table1 t1 LEFT JOIN Table2 t2 ON t1.LittleID = t2.LittleID AND t1.BigID = t2.BigID WHERE t1.BigID IN (1, 2, 3) AND t2.LittleID IS NULL GROUP BY t1.BigID ```
Making SQL query with multiple where conditions and variables more efficient
[ "", "sql", "sql-server", "" ]
I have a query that looks up a list of documents depending on their department and their status. ``` DECLARE @StatusIds NVARCHAR(MAX) = '1,2,3,4,5'; DECLARE @DepartmentId NVARCHAR(2) = 'IT'; SELECT ILDPST.name, COUNT(*) AS TodayCount FROM dbo.TableA ILDP LEFT JOIN dbo.TableB ILDPS ON ILDPS.IntranetLoanDealPreS...
Try this instead: ``` DECLARE @StatusIds NVARCHAR(MAX) = '1,2,3,4,5'; DECLARE @DepartmentId NVARCHAR(2) = 'IT'; SELECT ILDPST.name, COUNT(ILDP.IntranetLoanDealPreStateId) AS TodayCount FROM dbo.TableC ILDPST LEFT JOIN dbo.TableB ILDPS ON ILDPST.IntranetLoanDealPreStateTypeId = ILDPS.CurrentStateTypeI...
If you want to have all the records from TableC you need to left join all other tables to it, not left join it to the other tables. Also it's best to `INNER JOIN` the filtering table you create from `@StatusIds` rather then apply it through `IN`clause. Try this: ``` DECLARE @StatusIds NVARCHAR(MAX) = '1,2,3,4,5'; DECL...
Returning column with count of 0
[ "", "sql", "sql-server", "t-sql", "" ]
In the table JAN07, I have a column TEMPO\_INTERCORSO (number(10,0)) and I want to create another column ANTE\_POST (number(1)) that is '0' when TEMPO\_INTERCORSO > 0 and '1' otherwise. ``` IF (TEMPO_INTERCORSO > 0) THEN UPDATE JAN07 SET ANTE_POST = 1 ELSE UPDATE JAN07 SET ANTE_POST = 0 END IF; ``` I've tried a...
The following `UPDATE` query uses `CASE...WHEN` to achieve what you want: ``` UPDATE JAN07 SET ANTE_POST = CASE WHEN TEMPO_INTERCORSO > 0 THEN 1 ELSE 0 END ```
I would rather suggest **[Virtual Columns](http://docs.oracle.com/cd/E11882_01/server.112/e41084/statements_7002.htm#BABCHBHE)** introduced in `Oracle Database 11g Release 1`. A simple **CASE** statement would do the rest. For example, ``` SQL> CREATE TABLE t 2 ( 3 TEMPO_INTERCORSO NUMBER, 4 ANTE_P...
IF-ELSE statement: create a column depending on another one
[ "", "sql", "oracle", "if-statement", "plsql", "sql-update", "" ]
This is my sql table: [SQLFiddle](http://sqlfiddle.com/#!9/3ff1c/3) I trying get `id_user` once, but with two or more conditions in `WHERE` clause If I use this code: ``` SELECT DISTINCT id_user FROM base_group_details WHERE id_category=3 ``` I getting good result, but i wanted getting result with two or more param...
I guess this is what you want ``` SELECT DISTINCT id_user FROM base_group_details WHERE id_category=3 and id_user IN ( SELECT DISTINCT id_user FROM base_group_details WHERE id_category = 4 ) ``` The Output is id\_user 1 and 3
No single row can have a category of both 3 and 4, so no rows are returned. One way to solve these types of questions is to group the result and count the number of relevant distinct categories each user has: ``` SELECT id_user FROM base_group_details WHERE id_category IN (3, 4) HAVING COUNT(DISTINCT id_category) =...
mysql select once (DISTINCT not working)
[ "", "mysql", "sql", "select", "" ]
I've got a table of purchasing decisions that looks like this: ``` org_id item_id spend -------------------------- 123 AAB 2 123 AAC 4 124 AAB 10 124 AAD 5 ``` I want to find all the items that were only bought by three or fewer organisations, then I wa...
Try query like this. In the result set you will see all items that were bought by there or fewer organisations and total spend ``` SELECT T2.org_id, T.item_id FROM table AS T2 JOIN (SELECT item_id, SUM(spend) AS total_spend FROM table AS T GROUP BY T.item_id HAVING COUNT(DISTINCT org...
In BigQuery - **JOIN**s sometimes is quite a headache (depends on multiple factors), so it is always good to have some non-join solutions in your arsenal. Below are few examples of such based on [Window functions](https://cloud.google.com/bigquery/query-reference#windowfunctions) : I think they can be interesting bo...
SQL: how to join multiple queries together?
[ "", "sql", "google-bigquery", "" ]
I have products with different details in different attributes and I need to develop an algorithm to find the most similar to the one I'm trying to find. For example, if a product has: * Weight: 100lb * Color: Black, Brown, White * Height: 10in * Conditions: new Others can have different colors, weight, etc. Then I ...
What you want to do is a perfect use case for [elasticsearch](https://www.elastic.co/products/elasticsearch) and other similar search oriented databases. I don't think you need to hack with bitmasks/etc. You would typically maintain your primary data in your existing database (sql/cassandra/mongo/etc..anything works),...
You basically need to come up with a distance metric to define the distance between two objects. Calculate the distance from the object in question to each other object, then you can either sort by minimum distance or just select the best. Without some highly specialized algorithm based on the full data set, the best ...
Similarity matching algorithm
[ "", "sql", "algorithm", "performance", "categories", "" ]
The question is, Determine names of all the ships in Ships table that meet a combination of at least four criteria from the following list: numGuns = 8 bore = 15 displacement = 32000 type = bb launched = 1915 class = Kongo country = USA. I found the answer for this exercise. The answer is, ``` SELECT s.name from sh...
The cast from `boolean` to `integer` yields 0 or 1: ``` select s.name from ship s inner join classes c using (class) where (numguns = 8)::int + (bore = 15)::int + (displacement = 32000)::int + (type = 'bb')::int + (launched = 1915)::int + (class = 'Kongo')::int + (country = 'U...
You can use `CASE WHEN` statements to count the number of matching columns for each record, and then wrap this query to get only records with 4 or more matching columns. ``` SELECT t.name FROM ( SELECT s.name, CASE WHEN s.numGuns = 8 THEN 1 ELSE 0 END AS c1, CASE WHEN s.dbore = 15 THEN 1 ELSE 0 END...
SQL : 4 conditions combined with OR
[ "", "sql", "postgresql", "" ]
I have two tables - client and person. They are linked by `personID` in both tables. I am trying to create a view. I tried: ``` SELECT * FROM client INNER JOIN person ON client.personID = person.personID ``` It didn't like it saying `Duplicate column name 'personID`. I thought if you used `table.column` that was f...
It looks like you have to alias you'r column names with aliases. ``` SELECT client.column1 as col1, client.column2 as col2, person.column1 as colp1 FROM client INNER JOIN person ON client.personID = person.personID ``` Of course, replace the column names into the real column names as use more appealing aliases Let u...
``` SELECT c.*, p.`all`, p.need, p.`fields`, p.`of`, p.person, p.`table`, p.without, p.personID_field FROM client c INNER JOIN person p ON p.personID = c.personID ```
Alias for column name on a SELECT * join
[ "", "mysql", "sql", "join", "alias", "" ]
The tables I am working on contain details about their treatment and details abour appointments, named vwTreatmentPlans and vwAppointmentDetails respectively. My aim is to return one row per patient code only. I want it to display two columns: the patient code from the vwTreatmentPlans table and the appointmentDateTim...
Why are you grouping by `vA.appointmentDateTimevalue`? You needn't do it. So you can get your result set with next query ``` SELECT vT.PatientCode, MAX(vA.appointmentDateTimevalue) as max_date FROM vwTreatmentPlans vT INNER JOIN vwAppointmentDetails vA ON vT.PatientCode = vA.patientcode WHERE vT.[Current]...
All the data you show (`PatientCode` and `appointmentDateTimevalue`) is available in table `vwAppointmentDetails`. So select from that table. The criteria which records to select are in table `vwTreatmentPlans`, so have it in the where clause. ``` select patientcode, max(appointmentdatetimevalue) from vwappointmentde...
SQL - Join two tables and return one row only contain the latest time from the second table
[ "", "sql", "join", "greatest-n-per-group", "" ]
I wonder why one should ever care on explicitly writing an index in query. I frequently see queries like this ``` select blabla from Table with(nolock index = index_name) ``` Index is already defined, and query optimizer chooses the best index by itself. Isn't it more logical and efficient to write query as this: ``...
This is question is kind of rhetoric: one must measure efficiency, not reason about it. In ssms you can do it with "Include Actual Execution Plan" (Ctrl-M). Try execute following in ssms and look at "Execution plan": ``` SELECT * FROM msdb.dbo.sysjobs with (index = nc1) SELECT * FROM msdb.dbo.sysjobs with (index = ...
Specifying Index in the SQL SERVER causes Force Seeking of that Index. > When any query is ran SQL Server Engine determines which index has to > be used. SQL Server makes uses Index which has lowest cost based on > performance. Index which is the best for performance is automatically > used. There are some instances w...
Advantages of explicitly writing an index
[ "", "sql", "sql-server", "t-sql", "indexing", "sql-server-2008-r2", "" ]
I have a table with columns as follows.. 1. id 2. person1 3. person2 let's say there are 2 records having values... ``` id1 - 2222 - 4444 id2 - 3333 - 6666 ``` I want to modify the value of that cell whose value is '4444' and id is 'id1'
You could use a `case` expression on only update the appropriate columns: ``` UPDATE mytable SET person1 = CASE person1 WHEN '4444' THEN 'new value' ELSE person1 END, person2 = CASE person2 WHEN '4444' THEN 'new value' ELSE person2 END WHERE id = 'id1' AND '4444' IN (person1, person2) ```
@Mureinik has given the answer. But as you asked for other 49 columns how to make this query then you can prepare the dynamic query and then execute it. Below is the same query mentioned by @Mureinik but created dynamically: ``` SET @sql = NULL; SELECT GROUP_CONCAT(DISTINCT CONCAT(UN.column_name, ' =...
how to find a specific column name from a table whose column value is matched?
[ "", "mysql", "sql", "sql-update", "" ]
I have a PostgreSQL table with the following relevant fields: ``` url title created_at ``` There can be many rows that contain identical URLs but different titles. Here are some sample rows: ``` www.nytimes.com | The New York Times | 2016-01-01 00:00:00` www.wsj.com | The Wall Street Journal | 2016-01...
Try; ``` select t1.url, t2.title, t1.cnt from ( select url, count(title) cnt from headlines group by url ) t1 join ( select distinct on (url) url, title from headlines order by url, created_at desc ) t2 on t1.url = t2.url order by t1.url ``` `join` both queries on `url` [**`sql fiddle demo`**](http:/...
This can be done in a single `SELECT` with a single scan over the table - by combining a [window function](http://www.postgresql.org/docs/current/interactive/functions-window.html) with `DISTINCT ON`: ``` SELECT DISTINCT ON (url) url, title, count(*) OVER (PARTITION BY url) AS ct FROM headlines ORDER BY ur...
Run Postgres query that groups by one field and sorts by another
[ "", "sql", "postgresql", "aggregate", "greatest-n-per-group", "window-functions", "" ]
I have the following UPSERT in PostgreSQL 9.5: ``` INSERT INTO chats ("user", "contact", "name") VALUES ($1, $2, $3), ($2, $1, NULL) ON CONFLICT("user", "contact") DO NOTHING RETURNING id; ``` If there are no conflicts it returns something like this: ``` ---------- | id | --------...
I had exactly the same problem, and I solved it using 'do update' instead of 'do nothing', even though I had nothing to update. In your case it would be something like this: ``` INSERT INTO chats ("user", "contact", "name") VALUES ($1, $2, $3), ($2, $1, NULL) ON CONFLICT("user", "contact") DO ...
The [currently accepted answer](https://stackoverflow.com/a/37543015/939860) seems ok for a single conflict target, few conflicts, small tuples and no triggers. It avoids ***concurrency issue 1*** (see below) with brute force. The simple solution has its appeal, the side effects may be less important. For all other ca...
How to use RETURNING with ON CONFLICT in PostgreSQL?
[ "", "sql", "postgresql", "upsert", "sql-returning", "" ]
I have a table called test. In test I have An ID, a value and a date. The dates are ordered for each ID. I want to select rows for an ID, before and after a change of value, so the following example table. RowNum--------ID------- Value -------- Date 1------------------001 ---------1----------- 01/01/2015 2--...
You could use analytic functions `LAG()` and `LEAD()` to access value in preceding and following rows, then check that it does not match value in current row. ``` SELECT * FROM ( SELECT RowNum, ID, Value, Date, LAG(VALUE, 1, VALUE) OVER(ORDER BY RowNum) PrevValue, LEA...
Refer the below one for without using LEAD and LAG: ``` DECLARE @i INT = 1, @cnt INT, @dstvalue INT, @srcvalue INT CREATE TABLE #result ( id INT, mydate DATE ) CREATE TABLE #temp1 ( rn INT IDENTITY(1, 1), id INT, mydate DATE ...
SQL - Selecting rows with dates before and after column value change
[ "", "sql", "sql-server", "" ]
I'm using a T-SQL script to remove all constraints and all tables in my database to give me a clean slate upon execution, it seems to work fine for constraints, but when adapting the segment to clear my tables out it's giving me an error message, code is as follows: ``` declare @tableCommand varchar(255) declare tabl...
I think you miss some brackets: ``` while @@fetch_status = 0 begin exec (@tableCommand); fetch next from tableCursor into @tableCommand end ```
I won't use `CURSOR` to do this. ``` SELECT ' Drop table ' + s.NAME + '.' + t.NAME FROM sys.tables t JOIN sys.schemas s ON t.[schema_id] = s.[schema_id] WHERE t.type = 'U' Exec sp_executesql @sql ``` **Note:** If you have any `foreign Keys` defined between tables then you have to disable it befor...
T-SQL dropping multiple tables
[ "", "sql", "sql-server", "t-sql", "" ]
If I have following query ``` if not exists(select * from DeliveryTemplate where TemplateId=2) begin select usersCode, 1,2,'User {UsersCode}',' hello {Username},', null from User end ``` how can I extend th...
So you need to use `JOIN` something like: ``` if not exists(select * from DeliveryTemplate where TemplateId=2) begin select u.usersCode, 1,2,'User {UsersCode}',' hello {Username},', null, dt.DeliveryCode from User u left join DeliveryTemplate d...
``` declare @count int declare @DeliveryCode nvarchar(100) select @count = count(*), @DeliveryCode = DeliveryCode from DeliveryTemplate where TemplateId=2 if @count = 0 begin select usersCode, 1, 2, 'User {UsersCode}', ...
select data from two tables using simple sql query
[ "", "sql", ".net", "sql-server", "t-sql", "" ]
Suppose if i have a table A with 100 columns of same data type and 100 rows. Table B with 2 columns and 5000 rows of same data type of above table columns. Which table takes more disk space to store & which is more efficient?
The real answer here is... it depends. Oracle stores its data in "data blocks", which are stored in "Extents" which are stored in "Segments" which make up the "Tablespace". [See here.](https://docs.oracle.com/cd/B19306_01/server.102/b14220/logical.htm) A data block is much like a block used to store data for the oper...
Either a table has 2 columns or 100. You would not convert one into the other or you would do something very wrong. A product table may have 100 columns (item number, description, supplier number, material, list price, actual price ...). How would you make this a two column table? A key-value table? A very bad idea. ...
Which is more space efficient, multiple colums or multple rows?
[ "", "sql", "oracle", "database-design", "" ]
I am confused that how i can query this from table below. I have to get only those categories which is assigned to a single group. ``` **Id** **Category** **PracticeGroup** 1 Category-1 Practice Group-1 2 Category-1 Practice Group-1 3 Category-2 Practice...
Just can do this :- ``` select [category] from (select distinct [category] ,[Practice Group] from tbl) as temp group by [category] having count([category]) = 1 ```
You can use the same query what @potasin mentioned, with the min of Practice Group ``` select [Category],min([Practice Group]) from tbl group by [Category] having count(distinct [Practice Group]) = 1 ```
Select all rows having specific value assigned only once
[ "", "sql", "sql-server", "database", "sql-server-2014", "sql-server-2014-express", "" ]
I have two tables in my database which I need to join to obtain a list of User IDs. The first table stores the `user_id` and `email`: ``` user_id | email ------------------------- 1 | test@test.com 2 | test2@test.com ``` Table 2 contains searches of the user and the browser which they used: ``` id | user...
This will list all users that have at least one search from a browser that is not Internet Explorer: ``` SELECT u.id, u.email FROM users u WHERE EXISTS ( SELECT 1 FROM searches s WHERE s.user_id = u.id AND s.browser <> 'Internet Explorer' ) ```
Under the assumption that every user used at least one browser sometime, this can be done more easily by filtering the users where another browser exists: ``` SELECT DISTINCT u.userid, u.email FROM users u WHERE EXISTS (SELECT * FROM searches k WHERE u.userid = k.userid AND k.brows...
SQL query groupBy and filter
[ "", "mysql", "sql", "select", "pgadmin", "" ]
I can't see leading/trailing whitespace in the following following SQL statement executed with `psql`: ``` select name from my_table; ``` Is there a pragmatic way to see leading/trailing whitespace?
If you don't mind substituting all whitespace characters whether or not they are leading/trailing, something like the following will do it: ``` SELECT REPLACE(REPLACE(REPLACE(REPLACE(txt, ' ', '_'), E'\t', '\t'), E'\r', '\r'), E'\n', '\n') AS txt FRO...
One of option is to use format() function. With given query case: `select format( '"%s"', name ) from my_table;` PoC: ``` SELECT format( '"%s"', name ) FROM ( VALUES ( ' a ' ), ( ' b ' ) ) v(name); format -------- " a " " b " (2 rows) ```
How to show leading/trailing whitespace in a PostgreSQL column?
[ "", "sql", "postgresql", "whitespace", "psql", "" ]
Let's say I have the following database table: ``` id | from | to 1 | 01-JAN-2015 | 03-MAR-2015 1 | 04-MAR-2015 | 31-AUG-2015 1 | 01-SEP-2015 | 31-DEC-2015 2 | 01-JAN-2015 | 30-JUN-2015 2 | 01-NOV-2015 | 31-DEC-2015 ``` And I want to...
You can do it using hierarchical queries, something like this: ``` select id, min(root_dt_from) dt_from, dt_to from (select id, dt_from, dt_to, level, connect_by_isleaf, connect_by_root(dt_from) root_dt_from from t where connect_by_isleaf = 1 connect by prior id = id and prior (dt_to + 1)...
> You can try here some analytical functions which can really simplify > the scenario. Hope this below snippet helps. Let me know for any > issues. ``` SELECT B.ID, MIN(B.FRM_DT) FRM_DT, MAX(B.TO_DT) TO_DT FROM (SELECT A.ID, A.FRM_DT, A.TO_DT, NVL(LAG(A.TO_DT+1) OVER(PARTITION BY A.ID ORDER BY A.TO_D...
PL/SQL: How to convert multiple rows with continuous time frames into one single row convering the whole time frame?
[ "", "sql", "oracle", "plsql", "gaps-and-islands", "" ]
I have my query displaying output as displayed below ``` `UserName Status Count` `A Pass 32` `A fail 2` `A Hold 4` `B Fail 12` `C Pass 40` `C Fail 4` `C Hold 3` `D Pass 2` ``` I want to have output to...
To achieve the desired listing order is relatively simple: ``` select top 6 * from #tbl INNER JOIN ( SELECT UserName u, cnt pc FROM #tbl WHERE Status='Pass' ) ord ON u=UserName ORDER BY pc desc,status desc ``` However, limiting it to 5 rows, in case the first result sets are not complete, is not that easy. I am s...
``` ;WITH CTE_UserRanking AS ( SELECT UserID, DENSE_RANK() OVER (ORDER BY COUNT(*) DESC) AS user_rank FROM dbo.User_Scores S WHERE S.Status = 'Pass' GROUP BY UserID ) SELECT U.UserName, S.Status, COUNT(*) FROM CTE_UserRanking R INNER JOIN dbo.Users...
SQL Query to display records categorically
[ "", "sql", "sql-server", "sql-server-2012", "tabular", "" ]
``` FOR this_loop IN (SELECT field_A, field_B FROM TABLE_NAME WHERE num = i_num) LOOP IF this_loop.field_B BETWEEN 1 AND 3 THEN v_A := v_A || ' ' || this_loop.field_A; ELSIF this_loop.field_B BETWEEN 4 AND 8 THEN v_field_A := v_field_A || ' ' || this_...
> Variable v\_field\_A cannot hold value more than 100 characters Why not? It is very much possible since you are **concatenating** the variable for each row in the **CURSOR FOR LOOP**. For example, ``` SQL> DECLARE 2 v_name VARCHAR2(50); 3 BEGIN 4 FOR i IN 5 (SELECT ename FROM emp 6 ) 7 ...
You can do the string concatenation in a SQL query: ``` SELECT field_A, LISTAGG(CASE WHEN field_B BETWEEN 1 AND 3 THEN field_A END, ' ') WITHIN GROUP (ORDER BY field_A) as val1, LISTAGG(CASE WHEN field_B BETWEEN 4 AND 8 THEN field_A END, ' ') WITHIN GROUP (ORDER BY field_A) as val2, LISTAGG(CASE W...
ORA-06502: character string buffer too small. Even though the string size is under declared size limit
[ "", "sql", "oracle", "plsql", "oracle11g", "" ]
I have A table of students and their grades. How can I count the number of failed grades (*<50*) and find the general average ( I mean the average for every student ) using **sqlite**? this is the table (studentTable): ``` sID LessonID grade 1 1 45 1 2 50 1 3 65 2 1 44 2 2 ...
Try ``` SELECT sID, SUM(CASE WHEN grade < 50 THEN 1 ELSE 0 END) AS noOfFails, AVG(grade) AS Average FROM studentTable GROUP BY sID ``` Demo at <http://sqlfiddle.com/#!5/fcd13/1>
You could use a `case` expression inside the `count` function: ``` SELECT sID, COUNT(CASE WHEN grade < 50 THEN 1 END) AS noOfFails, AVG(grade) FROM mytable ```
How to find number of failed grades and the number of general average?
[ "", "sql", "sqlite", "select", "average", "" ]
I have query that is executing too long (more than 300sec). Can it be optimized with indexes or query modifying? What is the best key? ``` SELECT `streams_channel`.`id`, `streams_channel`.`uid`, `streams_channel`.`provider_id` FROM `streams_channel` WHERE `streams_channel`.`provider_id` = 1 AN...
The best index for this query is probably `streams_channel(provider_id, followers, id)`. You could also add `uid` so the index covers the query (that is, all the columns being used are in the index). However, this index will not prevent the final sort for the `ORDER BY`, which may be the performance issue. How many ro...
You need indexes on the columns in the WHERE clause. You can see the effect of changes by running EXPLAIN before and after. You should see TABLE SCAN removed by adding indexes. Order of WHERE clauses matters. Make the first clause eliminate the majority of the rows and make it easier for subsequent clauses.
Best key for a MySQL query on a large table (> 1M)
[ "", "mysql", "sql", "optimization", "indexing", "" ]
I have a Client data table, selected columns of which are shown below: ``` Row_ID Client_ID Status_ID From_date To_date 1 123456 4 20/12/2007 18:02 20/12/2007 18:07 2 789087 4 20/12/2007 18:02 20/12/2007 18:07 3 789087 4 20/12/2007 18:07 20...
As I understood, this is what you need: ``` select client_ID, status_id, from_date, to_date, sum(start_of_group) over (order by client_ID, from_date) + 1 rank from (SELECT c.client_ID, c.status_id, c.from_date, c.to_date, case when lag(c.client_ID, 1, c.client_ID) over (order by c.client_ID, c...
the thing is that you need to partition your ranking over the CHANGE of the status, not the VALUE of the status. I'm leaving some extra columns in the output so that you can see how it is all derived: ``` WITH dat as ( SELECT 1 row_id, 123456 client_id, 4 status, to_date('20/12/2007 18:02','dd/mm/yyyy ...
Oracle SQL - DENSE_RANK
[ "", "sql", "oracle", "dense-rank", "" ]
I have a postgres 9.3 table with two columns. The first column has times and the second has routes. A route may have multiple times. I want to list all routes with their most minimum times. My table: ``` Times Routes 07:15:00 Route a 09:15:00 Route a 08:15:00 Route b 11:30:00 Route b 09:15:00 Route...
This can be done using the [`MIN` aggregate function](http://www.postgresql.org/docs/8.0/static/functions-aggregate.html), and then grouping by the `Routes` column: ``` SELECT Routes, MIN(Times) FROM Table GROUP BY Routes ``` The `GROUP BY` clause is used to group rows together into a single row which have the same v...
``` select distinct on(routes) routes ,times from p order by routes,times asc ``` --- [`DISTINCT ON`](http://www.postgresql.org/docs/9.4/static/sql-select.html#SQL-DISTINCT) Will return the "*first*" row of each set of rows where the expression is equal. As per doc. > DISTINCT ON ( expression [, ...] ) kee...
POSTGRES min/least value
[ "", "sql", "postgresql", "aggregate-functions", "postgresql-9.3", "distinct-on", "" ]
I am looking for a way to find out the value of maximum character repetition in a string. For instance : ``` String NMCR ----------------------- akhsdjjjaajjj 6 AABBDDDDDDD 7 ```
An odd requirement, but here is a way: ``` create or replace function max_repetetive_letter_count (string varchar2) return integer is letter_col SYS.KU$_VCNT := SYS.KU$_VCNT(); -- A handy collection type l_max_count integer; begin letter_col.extend(length(string)); for i in 1..length(string) loop l...
My try, with steps highlighted by CTEs: ``` with data as (select 'akhsdjjjaajjj' txt from dual union all select 'AABBDDDDDDD' txt from dual ), chars as(select txt,substr(txt,lvl, 1) c, lvl from data join (select level lvl from dual connect by level < 10...
Calculating the number of maximum repetitive character in Oracle
[ "", "sql", "string", "oracle", "count", "" ]
Is it possible to group result of my sql SELECT statements without creating temp table to sum and group in one statement? I have a table saving the total of debit and credit amount for credit account No. and debit account No. and put zero for opposite field, I made first grouppage with below union select statement and ...
As you say your query is working, lets call your union query as a table ``` ( ...... ) myTable ``` then just create a subquery to get the final step ``` SELECT ACCNAME, CASE WHEN SUM(CREDIT - DEBT) < 0 THEN - SUM(CREDIT - DEBT) ELSE 0 END DEBT, CASE WHEN SUM(CREDIT - DEBT) > 0 THEN ...
If you want only one row per subquery, then remove the `group by`: ``` select 'CASH' as ACCNAME, sum(amount) AS DEBT, 0 as CREDIT FROM JOURNAL UNION ALL select 'BANK' as ACCNAME, 0 as DEBT, sum(amount) AS CREDIT FROM JOURNAL; ``` (Note: the `ACCNAME` values might be reversed.) Important: You should be using `UNI...
nested union select statement
[ "", "mysql", "sql", "derby", "javadb", "" ]
Here's a simplified example of my data: ``` Acct AddType Address ==== ======= ============ 1001 Home 1239 Maple 1001 Billing 456 Broadway 1002 Billing 1234 Main 1003 Home 1278 Walnut ``` I'm trying to create a SQL query that will give me one address for each account. It...
A simple (and efficient) way to do this is to use `union all` and some additional logic: ``` select t.* from table1 t where addtype = 'Billing' union all select t.* from table1 t where addtype = 'Home' and not exists (select 1 from table1 t2 where t2.acct = t.acct and t2.addtype = 'Billing'); ``` There are othe...
I've used self joins for things like this: ``` SELECT Acct, case when c.Address IS NOT NULL then c.Address else b.Address end as Address, * FROM Table1 a LEFT OUTER JOIN Table1 b ON a.Acct = b.Acct AND b.AddType = 'Home' LEFT OUTER JOIN Table1 c ON a.Acct = c.Acct AND c.AddType = 'Billing...
SQL query that will give me billing address for each account, but home address if there is no billing
[ "", "sql", "sql-server", "" ]
I have a table which contains historical records for the votes given to entrants in a competition. A simplified example of the structure is: ``` id | entrantId | roundId | judgeId ``` Some example data: ``` 401 | 32 | 3 | 4 402 | 32 | 3 | 5 403 | 35 | 3 | 4 404 | 32 | 4 | 4 405 | 36 | 3 | 4 406 | 36 | 3 | 10 ``` I ...
You can use correlated subquery: ``` SELECT * FROM tab t1 WHERE judgeId = 4 AND roundId = 3 AND NOT EXISTS (SELECT 1 FROM tab t2 WHERE t1.entrantId = t2.entrantId AND t2.roundId = 4); ``` `LiveDemo` Output: ``` ╔═════╦═══════════╦═════════╦═════════╗ ║ id...
You might use except but you won't get the ID. ``` select entrantId from table where roundId = 3 and judgeId = 4 except select entrantId from table where roundId = 4; ```
Select users who have records equal to y but not x
[ "", "sql", "sql-server", "t-sql", "" ]
I have Three tables: ``` Users { id | name | email } User_Group { User_id | group_id } Subscriptions {user_id, sub_level } ``` * User can be signed to more that User group. * User can be subscribed to more than subscription plan. Let's suppose we have: Table Users: ``` [1, John, john@email.com] [2, ...
One method is to use aggregation: ``` SELECT U.Username, U.email, MAX(G.group_id) FROM `Users` U INNER JOIN `User_Group` G ON U.id = G.user_id INNER JOIN `Subscriptions` S ON U.id = S.user_id GROUP BY U.Username, U.email HAVING MAX(G.group_id) = 3 AND MIN(G.group_id) = 3 ; -- condition on groups `...
``` SELECT U.username, U.email, G.group_id, S.sub_level FROM Users U INNER JOIN User_Group G ON G.user_id = u.id AND G.group_id = 3 INNER JOIN Subscriptions S ON S.user_id = U.id WHERE NOT EXISTS ( SELECT * FROM User_Group G2 WHERE G2.user_id = U.user_id AND G2.gr...
Advanced Inner Join between User, User_Group and Subscriptions Tables
[ "", "mysql", "sql", "database", "select", "inner-join", "" ]
i have the following situation. every row has a timestamp when it was written on table. now i want to evaluate per day how many rows have been inserted before 5 am and how many after. how can that be done??
You can use the HH24 format to get the hour in 24-hour time: ``` select trunc(created_Date) as the_day ,sum(case when to_number(to_char(created_Date,'HH24')) < 5 then 1 else 0 end) as before_five ,sum(case when to_number(to_char(created_Date,'HH24')) >= 5 then 1 else 0 end) as after_five from yourtable g...
Assuming your timestamp is a DATE column: ``` select trunc(date_written) as day , count (case when (date_written-trunc(date_written))*24 < 5 then 1 end) before_5_count , count (case when (date_written-trunc(date_written))*24 >= 5 then 1 end) after_5_count from mytable group by trunc(date_written) ```
count rows before time
[ "", "sql", "oracle", "evaluate", "" ]
I am using sql to try to only where value is in the column more than once. For example, If my table was to look like this, The Age column is showing 3 instances of the age '2'. ``` Increment | Agenda ------------------------------------- 2 | Minutes Previous Meeting 2 | Minutes Previous Meeting 2 ...
``` WITH cte as ( SELECT Age, Cat, ROW_NUMBER() OVER (PARTITION BY Age ORDER BY Cat) as rn FROM YourTable ) SELECT CASE WHEN rn = 1 THEN Age ELSE NULL END as Age, Cat FROM CTE ```
Odd request - but try using a Window Function. ``` SELECT (CASE WHEN RowNum <> 1 THEN NULL ELSE Age END ) Age ,Cat FROM ( SELECT ROW_NUMBER()OVER(PARTITION BY Age ORDER BY Cat) RowNum ,Age ,Cat FROM dbo.YourTable ) Inner `...
SQL Only show First value of (where value is in the column more than once)
[ "", "sql", "sql-server", "" ]
I received a workbook which contains two tables in power-pivot (one around one million rows, another 20 mill rows). I would like to rip this out (as anything really - but let's say a CSV) so that I can use it in R + PostGreSQL. I can't export to an Excel table as there are more than 1 million rows; and copy-pasting th...
[DAX Studio](https://daxstudio.codeplex.com/) will allow you to query the data model in an Excel workbook and output to various formats, including flat files. The query you'll need is just: ``` EVALUATE <table name> ```
I have found a working (VBA) solution [but greggy's also works for me too!] -> my table was too big to export in one chunk so I loop over and filter by 'month'. This seems to work and produces a 1.2 gb CSV after I append all together: ``` Function YYYYMM(aDate As Date) YYYYMM = year(aDate) * 100 + month(aDate) End...
Rip 20 million rows from Power Pivot ("Item.data")
[ "", "sql", "vba", "excel", "powerpivot", "" ]
I have a string in multiple URLs starting with two characters followed by between 1-6 numbers e.g. 'SO123456' This string is rarely in the same position within the URL. Following the string is either .html or whitespace. ``` SELECT SUBSTRING(URL,PATINDEX('%SO[0-9]%',URL),8) FROM Table WHERE URL LIKE '%SO[0-9]%' ``` ...
Not quite elaborated, but as a hint to get you started: ``` patindex = PATINDEX('%SO[0-9]%',URL) -> Index of the start of the pattern charindex = CHARINDEX('.html', URL, patindex ) -> Index of the first '.html' after the start of the pattern. patternLen = charindex - patindex ``` So something like the following may w...
I think you should check the length of the column first dude. Here's the code ``` SELECT CASE LEN(URL) -- Check the length of URL column WHEN > 8 THEN SUBSTRING(URL,PATINDEX('%SO[0-9]%',URL),8) ELSE -- do your stuff END as 'example' FROM Table ```
Parsing a URL to find a varying length string
[ "", "sql", "sql-server", "string", "parsing", "url", "" ]
I'm trying to join 2 tables to get an output report. The tables involved are the stock and dailysales table. Stock and Dailysales tables: [![enter image description here](https://i.stack.imgur.com/EW3gz.jpg)](https://i.stack.imgur.com/EW3gz.jpg) Desired output format: [![enter image description here](https://i.stac...
You can sum the item in a separated table, it would be clearer than `GROUP BY` 2 tables ``` SELECT s.item, s.article, ISNULL(ds.sold, 0) AS qtysold, s.stockonhand FROM stock s OUTER APPLY (SELECT SUM(sold) AS sold FROM dailysales WHERE item = s.item GROUP BY item) ds ```
Not tested - ``` select item,article,sum(sold),sum(stockonhand)-sum(sold) from ( select a.item,a.article,a.stockonhand,case when b.sold is null then 0 else b.sold end as sold from stock a left join dailysales b on (a.item = b.item)) group by item,article; ``` It's basically does the left join and put 0 on the null...
Joining 2 tables error
[ "", "sql", "join", "left-join", "inner-join", "" ]
I have a table with following Column ``` Name ---------------------- test10/20000020 test1/test2 / 20000001 test3/test4 / 20000002 test5/20000017 test5/test6 / 20000004 test5/20000007 ``` I need to select the last value I.e ``` 20000020 20000001 20000002 20000017 20000004 20000007 ``` I have tr...
SELECT SUBSTRING( Name, LEN(Name) - CHARINDEX('/',REVERSE(Name)) + 2 , LEN(Name) ) FROM SAMPLE worked for me
Using XML: ``` declare @xml xml; declare @str nvarchar(max) = ''; with data as ( select 'test1/test2/test3/344495' as r union ALL select 'test1/344556' as r ) select @str = @str + '<r><v>' + replace(r,'/','</v><v>') + '</v></r>' from data; -- obtain xml set @xml = cast(@str as xml); -- select last value from ea...
Get Last values using Select Substring in SQL Query
[ "", "sql", "sql-server-2008", "" ]
I'm kinda new into the SQL Server and I'm having the following question: is there any possibility to renumber the rows in a column? For ex: ``` id date name 1 2016-01-02 John 2 2016-01-02 Jack 3 2016-01-02 John 4 2016-01-02 John 5 2016-01-03 Jack 6 2016-01-03 Jack 7 2016-01-04 Joh...
I hope this helps.. ``` declare @t table (id int ,[date] date,name varchar(20)) insert into @t ( id, date, name ) values (1,'2016-01-02','John') ,(2,'2016-01-02','Jack') ,(3,'2016-01-02','John') ,(4,'2016-01-02','John') ,(5,'2016-01-03','Jack') ,(6,'2016-01-03','Jack') ,(7,'2016-01-04','John') ,(8,'2016-01-0...
The `id` should just be an internal identifier you use for joins etc - I wouldn't change it. But you could query such a numbering using a window function: ``` SELECT ROW_NUMBER() OVER (ORDER BY CASE name WHEN 'John' THE 1 ELSE 2 END) AS rn, date, name FROM mytable ```
Renumbering rows in SQL Server
[ "", "sql", "sql-server", "t-sql", "select", "" ]
I am using this SQL Server [database](https://gist.githubusercontent.com/pamelafox/ad4f6abbaac0a48aa781/raw/c72be44a1bdefcbaf8af63361f98595552131b9c/countries_by_population.sql). I am defining the following remarks for countries ``` CASE WHEN density_per_sq_km > 1000 THEN 'Overpopulated' WHEN density_per_sq_k...
In the group by clause you cannot use that column alias, use the case expression instead ``` SELECT COUNT(country) AS no_of_countries , CASE WHEN density_per_sq_km > 1000 THEN 'Overpopulated' WHEN density_per_sq_km > 500 THEN 'above average' WHEN density_per_sq_km > 250 TH...
Wrapping the query with computed column into a subquery may help you use that column: ``` SELECT remarks, COUNT(country) as no_of_countries FROM ( SELECT CASE WHEN density_per_sq_km > 1000 THEN 'Overpopulated' WHEN density_per_sq_km > 500 THEN 'above average' WHEN density_per_sq_km > 250 THEN ...
SQL Server : how to use count
[ "", "sql", "sql-server", "count", "case", "" ]
I do not understand why, but somehow this query doesn't work. I want to take system date -1 day where the sysdate is smaller by 1 day then current date. ``` WHERE a.SEND_Date >= dateadd(DD,-1,(CAST(getdate() as date) as datetime)) ```
The CAST depends on what kind of date type you need. If you need only to compare dates you can use only: ``` dateadd(DD, -1, cast(getdate() as date)) ``` If you need to compare with date time you can use: ``` dateadd(DD,-1,getdate()) ``` That wil give you datetime like this: `2016-01-11 10:43:57.443`
In T-SQL (sqlserver) you can simply do : ``` getDate()-1 ``` The function substracts (days) as standard.
Getdate(), -1 day
[ "", "sql", "sybase", "sqlanywhere", "" ]
I have a series of numbers stored in an oracle table in the following format. ``` Emp_ID 1 2 3 4 5 6 7 8 9 10 14 15 16 17 18 31 32 33 34 35 36 41 42 ``` I want to group this list by a fixed number like 7 and get the output in the following format: ``` Range Total 1-7 7 8-10,14-17 7 18-18,31-36...
If you need the range representation as shown in your example: ``` -- test data with data(empid) as ( -- complete list 1..42 select level from dual connect by level <= 42 minus ( -- minus gaps select level from dual where level between 11 and 13 connect by lev...
In Oracle 11g you could use `listagg()` and analytic functions: [SQLFiddle demo](http://sqlfiddle.com/#!4/8522e/1) ``` with t1 as ( select emp_id id,row_number() over (order by emp_id) rn from test), t2 as ( select id, rn, floor((rn-.1)/7) grp, min(id) over (partition by floor((rn-.1)/7), id-rn)|...
How to group a series of numbers in oracle sql, with a specific number provided
[ "", "sql", "oracle", "plsql", "" ]
First of all, I would like to apologize for the vague title of my question. It's very difficult for me to explain the situation, since I'm not an expert in SQL. I need help in writing a query. I have a table, called **HELLO-MESSAGES**, which contains several columns: *ID*, *From*, *To*, *Body*, *Sent* (with the data ...
As I indicated in my comments, for a table with a large number of rows, to improve query performance, I would consider implementing an additional "latest message" table to be maintained along with the `HELLO-MESSAGES` table. But I won't delve into that, since that doesn't address the specific question you were asking. ...
What you are looking for, I think is not that simple and you need to have good knowledge of sql. I think that the answer is in the following link: [Get Last conversation row from MySQL database table](https://stackoverflow.com/questions/8427198/get-last-conversation-row-from-mysql-database-table) Hope this helps you....
How to make a particular SELECT query
[ "", "mysql", "sql", "" ]
I'm trying to get count of duplicate data, but my query doesn't work correctly. Every user should have one dev\_id but when other user will have this same dev\_id I want to know this Table for example: ``` dev_id user_id ------------------ 111 1 111 1 222 2 111 2...
Okay. Let start from simple. First you need get unique user\_id/dev id combinations ``` select distinct dev_id,user_id from reports ``` Result will be ``` dev_id user_id ------------------ 111 1 222 2 111 2 333 3 ``` After that you should get number of differen...
You can get results by doing: ``` select r.user_id, count(*) - 1 from reports r group by r.user_id; ``` Is this the calculation that you want?
MYSQL Count of duplicate records with condition
[ "", "mysql", "sql", "" ]
I just spotted curious behaviour of oracle [TO\_DATE](https://docs.oracle.com/cd/B28359_01/server.111/b28286/functions191.htm) function when used with [format\_mask](https://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements004.htm#i34924) parameter. Basically, what I see is that in one case it ignores given ...
See the table here: <https://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements004.htm#g195479> It is part of the String-To-Date Conversion Rules section of the Datetime format model. In the case of `MM` if there is no match, it attempts for `MON` and `MONTH`. Similarly if you specify `MON` and it does not fi...
This is by design. Oracle tries to find deterministic date representation in the string even if does not comply with the defined mask. It throws the error only it doesn't find deterministic date or some required component of the date is missing or not resolved.
Oracle TO_DATE NOT throwing error
[ "", "sql", "oracle", "oracle12c", "" ]
Project configuration: * data base - MySQL 5.7 * orm - Hibernate 4.3.11.Final / JPA 1.3.1.RELEASE * Liquibase 3.4.2 My problem dont exist when i run script from workBeanch only from Liquibase. ``` <changeSet author="newbie" id="function_rad2deg" dbms="mysql,h2"> <sqlFile encoding="utf8" path="sql/function_rad2de...
If you are using yaml file then here is the configuration ``` changeSet: id: sqlFile-function author: sandeep logicalFilePath: baseFunctionScript changes: - sqlFile: dbms: mysql encoding: utf8 endDelimiter: \nGO path: my/path/baseScripts.sql splitStatements: true stripComm...
I think you need to add the `endDelimiter` clause in the Liquibase tag, based on the documentation found [here](http://www.liquibase.org/documentation/changes/sql_file.html) Below is an example ``` <changeSet author="newbie" id="function_rad2deg" dbms="mysql,h2"> <sqlFile encoding="utf8" path="sql/f...
Create function from SQL script by Liquibase
[ "", "sql", "function", "liquibase", "" ]
So i am just a beginner in all this php stuff. I know just the basics, and when i setting up the settings for my new table, I met the problem #1075. Before, i created one, almost similar to this one, and i don't see the differenc. Can you say me where is the problem and explain what is happening? ``` CREATE TABLE `try...
Try this ``` CREATE TABLE `testing` ( `id` INT NOT NULL AUTO_INCREMENT, `date` DATE NOT NULL, `text_1` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `text_2` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE = MYISAM ; ```
You have to declare your `AUTO_INCREMENT` field as a `primary key` or a `key`. So you have to add `PRIMARY KEY (id)` or `KEY (id)` to your `CREATE TABLE` statement: ``` CREATE TABLE `try`.`testing` ( `id` INT NOT NULL AUTO_INCREMENT, `date` DATE NOT NULL , `text_1` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NO...
#1075 MySQL Error
[ "", "mysql", "sql", "mysql-error-1075", "" ]
Say, I have a table like ``` Name Pets ------------------------- Anna Cats,Dogs,Hamsters John Cats Jake Dogs,Cats Jill Parrots ``` And I want to count, how many people have different types of pets. The output would be something like ``` Pets Owners --------------- Cats 3 Dogs 2 Hamsters 1 Parro...
It's a terrible design - as you mentioned - so I don't envy you having to work with it! It's possible to do what you're after, although I wouldn't like to say that it would be performant for larger datasets! Assuming the `name` column is the primary key (or at least unique): ``` with t1 as (select 'Anna' name, 'Cats...
It is a bad design to store **comma-separated** values in a **single column**. You should consider **normalizing the data**. Having such a design will always push you to have an overhead of manipulating delimited-strings. Anyway, as a workaround, you could use **REGEXP\_SUBSTR** and **CONNECT BY** to split the comma-d...
In oracle, how to 'group by' properties that are in comma separated values?
[ "", "sql", "oracle", "csv", "count", "group-by", "" ]
I am working on a sql oracle database. I have a table with an id, begindate and enddate. For example: ``` employee | begindate | enddate john | 18/02/2015 | 18/02/2015 john | 19/02/2015 | 21/02/2015 ``` I want to do a select statement of that table, but when the begindate is not equal to the enddate, it ...
**Oracle Setup**: ``` CREATE TABLE employees ( employee, begindate, enddate ) AS SELECT 'john', DATE '2015-02-18', DATE '2015-02-18' FROM DUAL UNION ALL SELECT 'john', DATE '2015-02-19', DATE '2015-02-21' FROM DUAL; ``` **Query**: ``` SELECT e.employee, t.COLUMN_VALUE AS begindate, t.COLUMN_VALUE AS en...
Here's an alternative answer using connect by directly on the table: ``` with test as (select 'john' employee, to_date('18/02/2015', 'dd/mm/yyyy') begindate, to_date('18/02/2015', 'dd/mm/yyyy') enddate from dual union all select 'john' employee, to_date('19/02/2015', 'dd/mm/yyyy') begindate, to_date('21/...
expand a row in different rows
[ "", "sql", "oracle", "" ]
I have a data set as below in `SQL Server`: ``` ROW_NUM EMP_ID DATE_KEY TP_DAYS 1 U12345 20131003 1 2 U12345 20131004 0 3 U12345 20131005 0 4 U12345 20131006 0 5 U12345 20150627 1 6 U12345 20150628 0 1 U54321 20131003 1 2 U54321 20131004 ...
Using windowed functions (`SUM/ROW_NUMBER` so it will work with `SQL Server 2008`): ``` WITH cte AS ( SELECT *, s = SUM(TP_DAYS) OVER(PARTITION BY EMP_ID ORDER BY ROW_NUM) FROM #tab ), cte2 AS ( SELECT *, tp_days_recalculated = ROW_NUMBER() OVER (PARTITION BY EMP_ID, s ORDER BY ROW_NUM) FROM cte ) UPDATE ...
Let me assume SQL Server 2012+. You need to identify groups that are delimited by 1. A simple way to calculate the group is by doing a cumulative sum of 1s. Then `row_number()` can be used to calculate the new value. You can do this work uisng an updatable CTE: ``` with toupdate as ( select t.*, row...
SQL - Update rows between two values in a column
[ "", "sql", "sql-server", "t-sql", "sql-update", "gaps-and-islands", "" ]
I am working on dates and got the requirement in this way. In case the recruit date is between 1st - 7th day of the month (e.g. July 3 2014), then the recruit date should be July 1 2014. In case the recruit date is after the 7th day of the month (e.g. July 8, 2014. Recruit date should be on the following month Aug 1 20...
There's no need for any complicated case statements, just use this code: ``` select trunc(add_months(ast.x_rec_dt,1)-7,'mm') RTD from employee ast where ast.row_id = '1-EWR'; ``` It first adds one month to the date in question, then subtracts 7 days from the new date, then truncates the whole thing to the beginnin...
Use a `CASE` statement to see if the date is on or before the 7th day of the current month. If it is not, add a month. This logic will show you how that works using all the dates in 2016 as test data. ``` WITH dates AS (SELECT TO_DATE ('01-JAN-2016') + ROWNUM - 1 dte FROM DUAL CONNECT BY ROWNU...
Rounding off dates in oracle
[ "", "sql", "oracle", "date", "" ]
``` select * from table where COALESCE(HOURS, MINUTES) is not null and (if hours = null, then minutes >0) and (if minutes = null then hours > 0) and (minutes != 0 AND hours != 0) ``` How can I give last 3 sqls as SQL condition for oracle? Sample data: ``` Hours Minutes ----- ------- 1 22 null 33 0 13 0 ...
Thanks guys, based on your suggestions, i am able to fetch proper data. I am using conditions like: select \* from table where condition1 and (COALESCE(HOURS, MINUTES) is not null) and (HOURS > 0 OR MINUTES > 0)
I suspect that you want: ``` where coalesce(hours, 0) + coalesce(minutes, 0) > 0 ``` This basically treats `NULL` as 0 and makes sure that the sum is greater than zero.
SQL to get data with condition as combination of two columns in oracle
[ "", "sql", "oracle", "" ]
I have a table Test and it`s data is : ``` A B 1 One 2 One 2 Two 3 One 2 One 5 Two 2 Three 2 Two 2 Three 2 Two 2 One ``` Now i want the output like following : ``` A B 10 One 10 One 11 Two 10 One 10 One 11 Two...
``` SELECT SUM(A) OVER (PARTITION BY B), B FROM Test ```
``` select t1.B, t2.sum_a FROM Test t1 join (select b, sum(a) as sum_a from test group by b) t2 on t1.b = t2.b ```
Getting duplicates values and summing up of 2nd column in SQL
[ "", "sql", "sql-server", "" ]
Background info: *We have a community room, which can be divided in half via a curtain. In the past when a group needed the full room we put 2 entries in, one for each half... However we've modified the software (MRBS) so that there are now 3 rooms (Full{1},Closet Side{2}, and Kitchen Side{3}) and the software checks t...
**Method 1 - Stored Procedure with temporary table** This seems the simplest method if you're prepared to use a Stored Procedure and temporary table: ``` CREATE PROCEDURE sp_sanitize_mrbs() BEGIN DROP TEMPORARY TABLE IF EXISTS mrbs_to_sanitize; CREATE TEMPORARY TABLE mrbs_to_sanitize ( id int auto_incre...
You can't use the table name for an update in the line for SET. You could probably get away with changing that line to just ``` SET `room_id` = '1' ``` But this is probably safer from the standpoint of ensuring the query works like you want it to: ``` UPDATE `mrbs_entry` set `room_id` = '1' WHERE `id` IN ( SELE...
UPDATE and DELETE a set of rows when the operations affect the set
[ "", "mysql", "sql", "" ]
How can I join two tables together to get all rows from each, and enter NULL, where one is missing in the other one. For example: ``` declare @t1 table (x int) declare @t2 table (x int) insert into @t1 select 2 insert into @t1 select 3 insert into @t1 select 4 insert into @t1 select 5 insert into @t2 select 1 inser...
``` select * from @t1 t1 full outer join @t2 t2 on t2.x = t1.x ``` this is like left join, but will take all the records from both table even when there is no match, and will enter null when there is no match.
``` select * from @t1 t1 FULL OUTER join @t2 t2 on t2.x = t1.x ```
Left/right join to receive all rows
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I have a table that looks like `Items`: ``` id index 1 45 1 50 2 25 2 45 ``` I am writing a query that select all rows from `items`. I need to replace the index with its description. Id 1 indicates table\_a, id 2 indicates table\_b. Table\_A ``` index description 45 'ddd' 50 'f...
You have to UNION Table\_A & Table\_B first, then join with Items as follows ``` Select id,index,T.description from items join (select 1 as id, index, description from Table_A UNION select 2 as id, index, description from Table_B) as T ON items.id=T.id and items.index=T.index ```
Assuming that UNION doesn't count as a join, then: ``` SELECT i.id, i.index, u.description FROM Items AS i JOIN (SELECT 1 AS id, index, description FROM Table_A UNION SELECT 2 AS id, index, description FROM Table_B ) AS u ON u.id = i.id AND i.index = u.index; ```
Conditional join from different tables
[ "", "sql", "postgresql", "" ]
Note: This is for a personal project to help in self learning, it does not involve work or schooling. I'm new to creating/databases and I'm looking for insight in how I could design the most logically sound table relationships. To give a bit of background information: I want to design a database that will hold differ...
I would go for: ``` **Drinks table** ID name description category_id //foreign key to a category table type_id //foreign key to a type table **Category** //Beer, Cocktails, etc ID Name **Type** //Pale ale, Lager, etc. ID Name **Ingredients** //Hold all ingredients Id desc...
Remove the Cocktails and Beers tables. Those are just different drinks, and you can add an "Instructions" field to the Drink table for the cocktails. The Ingedients table is the right way to handle ingredients. I'd just a numeric field for qty and text field for measurement (ie: 2 oz)
Database with variable number of fields in a table
[ "", "mysql", "sql", "database", "relationship", "normalization", "" ]
Is there a way to get DBeaver to use SQL Server's alternate "GO" delimiter? Squirrel SQL allows this via a SQL Server preference (statement separator).
This should work. * Open connection editor * click on "Edit Driver". * Switch tab on "Adv. parameters". * Set "Script delimiter" value to "go". [GO batch support](https://github.com/serge-rider/dbeaver/issues/192)
@Jonathan's screen seems to not exist anymore with actual version. This works for me : * Right click on your connection and select "Edit Connection". * Under SQL Editor -> SQL Processing, click the checkbox for "Datasource settings" and then change the "Statements delimiter" to "GO".
DBeaver SQL Server GO invalid
[ "", "sql", "sql-server", "dbeaver", "" ]
Hi I am using following Sql statement to calculate salary ``` DECLARE @startDate DATETIME, @endDate DATETIME, @currentDate DATETIME, @currentDay INT, @PerDaycount INT, @Monthcount INT DECLARE @currentMonth INT, @lastDayOfStartMonth INT CREATE TABLE #VacationDays ([Month] VARCHAR(10), [DaysSpent] INT,[MonthDays] VA...
Hi you can use this query. ``` DECLARE @startDate DATETIME, @endDate DATETIME, @currentDate DATETIME, @currentDay INT, @PerDaycount INT, @Monthcount INT DECLARE @currentMonth INT, @lastDayOfStartMonth INT CREATE TABLE #VacationDays ([Month] VARCHAR(10), [DaysSpent] INT,[MonthDays] VARCHAR(10),[PerdayAmt] de...
Please re-calculate month day after while loop execution, because your while loop not include last month, Add this line after while loop ``` SELECT @lastDayOfStartMonth = DATEPART(dd, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@currentDate)+1,0))) ```
Salary calculation in sql server
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I know this is a very easy question but i need someone to explain the thought process behind this query. I have a big table of data related to countries. I want to see which country has the minimum population so i use the following query ``` SELECT country, MIN(population) AS min_pop FROM countries_by_population; ``` ...
SQL is about query, i.e., filter and read/write. 1. When you do: `SELECT country, MIN(population) AS min_pop FROM countries_by_population;` you intended to select countries with the minimum population, and that logic is right--"select countries" and "with the minimum population". However what's going on here is...
The [GROUP BY](http://www.tutorialspoint.com/sql/sql-group-by.htm) requires the columns specified in the mathematical functions to be specified in it. Example: Consider **Employee** table ``` SELECT NAME, SUM(SALARY) FROM CUSTOMERS GROUP BY NAME; ``` This will return a result something like this ``` +----------+---...
How to select the country with the min population
[ "", "sql", "min", "" ]
There are two table `x_ass_table` and `i_ass_table` : I am inserting data from `x_ass_table` with 13000 records to i\_ass\_table: There is a unique constraint in `i_ass_table` ``` CREATE UNIQUE INDEX i_ass_table_pk ON i_ass_table(ASSIGNMENT_NUMBER,EFFECTIVE_START_DATE,EFFECTIVE_END_DATE,EFFECTIVE_LATEST_CHANGE) in...
You could number the source rows by combination of the fields you want unique using the analytic version of the `count()` function and then query to see which combination has more than one row. E.g.: ``` SELECT * FROM (SELECT *, COUNT() OVER (PARTITION BY assignment_number, ...
As you asked, you will have to check in both tables for the unique constraint conflict. 1. First check in `x_ass_table` if there is any duplicate record based in unique key, that you can check with query provided by Mureinik on above answer. 2. Second, you will have to check if there is same record present in both tab...
Unique key constraint error while inserting in SQL
[ "", "sql", "oracle", "oracle-sqldeveloper", "unique-key", "" ]
In my application i need to assign multiple groups to my users. There are 1000+ users and 10-15 groups. Which database design is better? One-to-many: ``` USER_ID | GROUP_1 | GROUP_2 | ... | GROUP_15 -------------------------------------------- 1 | true | false | ... | true 2 | false | true | .....
The many-to-many is the better design without a doubt. The first design makes writing queries difficult. Consider the following routine queries. 1. Is a specified user in a specified group? To do this you have to use a different query for each group. This is undesirable. Also if you are using column names for groups,...
If you want to follow the rules of an entity relationship model: ``` Many-to-many: users can belong to different groups & groups can have multiple users. One-to-many: a user belongs to one group & groups can have multiple users. ``` Your second example is a many-to-many, your first isn't a one-to-many. A one-to-many...
Database design. One-to-many or Many-to-many?
[ "", "mysql", "sql", "database", "sqlite", "relational-database", "" ]
I have searched a bit, and can't see any questions asked that answer my question, so here it goes. I am trying to get a date from the database (source is in datetime format, i.e "2015-11-30 00:00:00.000") and select it as date, but in another format. I am using Convert function for this after "googleing". First I set ...
Well, if you use ``` Select convert(varchar(10),ac_payout_book_dt,104) as 'Dato' ``` then you convert your `DateTime` (which internally in SQL Server has no format - it's an 8-byte binary value) to a string - you can control how the date is formatted into the string. In order to sort your output, you need a date...
i guess you should try this, order with `CAST` Date so by this way you will perform your desired operation and you will be able to get your desired date format as well. ``` SELECT CONVERT(VARCHAR(10), ac_payout_book_dt, 104) as 'Dato' ORDER BY CAST(ac_payout_book_dt AS DATE) DESC ```
sql - date not in format specified
[ "", "sql", "sql-server", "date", "select", "" ]
I am using Microsoft SQL Server 2014. The following is my query ``` SELECT type, SUM(calories) AS total_calories FROM exercise_logs GROUP BY type HAVING total_calories > 150; ``` and I get the error > Msg 207, Level 16, State 1, Line 2 > Invalid column name 'total\_calories'. Can somebody point out what am I doing...
`Aggregation` is required , as you have no access to alias `total_calories` ``` SELECT type,SUM(calories) AS total_calories FROM exercise_logs GROUP BY type HAVING SUM(calories) > 150; ```
You can also wrap the `GROUP BY` query up in a derived table: ``` select type, total_calories FROM ( SELECT type, SUM(calories) AS total_calories FROM exercise_logs GROUP BY type ) AS dt WHERE total_calories > 150 ```
'invalid column name' while using the HAVING
[ "", "sql", "sql-server", "t-sql", "having", "" ]
I found this MySQL function for [Base58](https://en.wikipedia.org/wiki/Base58) Encoder in a [Github Gist](https://gist.github.com/micahwalter/d6c8f8bc677978cf01a5). ``` DELIMITER $$ CREATE FUNCTION base58_encode (num int) RETURNS varchar(255) DETERMINISTIC BEGIN DECLARE alphabet varchar(255); DECLARE base_coun...
Equivalent function in PostgreSQL that I came up with is as follows. ``` CREATE FUNCTION base58_encode(num INT) RETURNS VARCHAR(255) AS $encoded$ DECLARE alphabet VARCHAR(255); base_count INT DEFAULT 0; encoded VARCHAR(255); divisor DECIMAL(10, 4); mod INT DEFAULT 0; BEGIN alphabet := '1...
For completeness here's a quick and dirty swipe at the inverse `base58_decode()` function: ``` CREATE OR REPLACE FUNCTION base58_decode(str VARCHAR(255)) RETURNS BIGINT AS $$ DECLARE alphabet VARCHAR(255); c CHAR(1); p INT; v BIGINT; BEGIN alphabet := '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUV...
Base58 Encoder function in PostgreSQL
[ "", "mysql", "sql", "postgresql", "base58", "" ]
I have data as `Decimal(15,4)` and values can be like `14.0100`, or `14.0000`, or `14.9999` For integration with other system we have to store this kind of data in `NVarChar(MAX)` attributes table. When I run `CAST(Field AS NVarChar(MAX))` I get string values like `0.0000` What I want is to trim trailing zeros (and p...
`SQL Server 2012+` you could use `FORMAT`, with `SQL Server 2008` you could use string manipulation: ``` CREATE TABLE #tab(col DECIMAL(15,4)); INSERT INTO #tab(col) VALUES (14.0100), (14.0000), (14.9999), (10), (0), (-1), (-10), (-12.01), (-12.10); SELECT col ,result_2012 = FORMAT(col, '########.##...
``` --With a lot of fantasy --Tip: to optimize performances, first select values in a @-table, then do this transformation. select left( cast(Field as varchar(max)), charindex('.', cast(Field as varchar(max))) - 1) + Case when reverse(cast(cast(reverse(substring(cast(Field as varchar), charindex('.', cast(Field a...
Remove trailing 0 when CAST as NVarChar
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
Hi I have the below query in Teradata. I have a row number partition and from that I want rows with rn=1. Teradata doesn't let me use the row number as a filter in the same query. I know that I can put the below into a subquery with a `where rn=1` and it gives me what I need. But the below snippet needs to go into a la...
Have you considered using the QUALIFY clause in your query? ``` SELECT cust_grp_id , fc_id FROM table1 QUALIFY ROW_NUMBER() OVER (PARTITION BY cust_grp_id ORDER BY eff_to_dt desc) = 1; ```
Calculate `MAX` `eff_to_dt` for each `cust_grp_id` and then join result to main table. ``` SELECT T1.cust_grp_id, T1.fc_id, T1.eff_to_dt FROM Table1 AS T1 JOIN (SELECT cust_grp_id, MAX(eff_to_dt) AS max_eff_to_dt FROM Table GROUP BY cust_grp_id) AS T2 ON T2.cust_grp_id = T1.cust_g...
Different way of writing this SQL query with partition
[ "", "sql", "teradata", "" ]
I am currently trying to export some data from SQL Server 2014 to a XML document. I've gotten help from here earlier on this project and I am very thankful for that. At the moment the data is structured correctly and is as it should be, but unfortunately the server (Totalview server) that is picking up the XML documen...
The answer to this question, is to disable column header when exporting to a file. In my case i am using Microsoft SQL 2014, so i went in to Tools->Options->Query Results->Results to Text, then remove the tick in 'Include Column headers in the result set' Even though the Totalview server still wont accept the output f...
You could try something like this. Keeping in mind that your exported XML file needs a root element and you need permissions to execute xp\_cmdshell. Thanks to [How To Save XML Query Results to a File](https://stackoverflow.com/questions/18775005/how-to-save-xml-query-results-to-a-file) ``` DECLARE @xml AS XML = (SELE...
SQL Server stamp on exporting FOR XML
[ "", "sql", "sql-server", "xml", "stamp", "" ]